June 2018
Beginner
722 pages
18h 47m
English
By contrast with List, it is not possible to replace an element in Set directly, because you cannot use index or another way to point to the object. But it is possible to iterate through the set as was described previously, or by using a Stream object (we will discuss this in Chapter 18, Streams and Pipelines) and check each element and see if this is the one you are looking to replace. Those elements that did not match the criteria, you can add to a new set. And those you would like to replace, skip and add another object (that will replace the one you skip) to the new set:
Set<String> set = new HashSet();set.add(null);set.add("s2");set.add("s3");System.out.println(set); //[null, s3, s2]//We want to replace s2 with s5 ...
Read now
Unlock full access