Lets discuss some methods commonly used with Sets in java
addAll is used to add one set to another
union.addAll(cubes); //where union and cubes are 2 two
retainAll is used to find common elements between two sets ``` intersection.retainAll(cubes);
So above we have intersection as one set and cubes as another and above command will create a new Set which will contain only the elements
that were common between two sets. Please note retainAll is a destructive operation so new Set will only contain common elements and original
intersection set will be lost
Passing String literal to a Set - We can't add elements to a Set all at once(i.e using a String literal) so we can first create a String to an array based
on spaces and then convert that array to ArrayList and then pass that list to Set using addAll
String sentence = "A day in the life of programmer";
String[] arrayWords = sentence.split(" ");
words.addAll(Arrays.asList(arrayWords)); //words is a Set
removeAll gives the asymmetric difference i.e creates a new Set that contains all elements in SetA but removes all elements from SetB that were also present in SetB.And it is a destructive operation i.e it changes SetB so better to copy SetB to new Set as we have done in diff2 below
Set<String> diff2 = new HashSet<>(SetA);
diff2.removeAll(SetB);
But instead there is a workaround. Create a union of two Sets using addAll.And then create a Set that only contains common elements and then remove common elements from the union.
Set<String> unionTest = new HashSet<>(SetA);
unionTest.addAll(SetB);
System.out.println("===========Intersection================");
Set<String> intersectionTest = new HashSet<>(SetA);
intersectionTest.retainAll(SetB);
System.out.println("===========symmetric diff================");
unionTest.removeAll(intersectionTest);
if(SetA.containsAll(intersectionTest)){
System.out.println("intersectionTest is subset of SetA");
}