For Each: Set Interface Bulk Operations
For Each: Set Interface Bulk Operations
For Each: Set Interface Bulk Operations
import java.util.*;
public class FindDups {
public static void main(String[] args) {
Set<String> s = new HashSet<String>();
for (String a : args)
s.add(a);
System.out.println(s.size() + " distinct words: " + s);
}
}
s1.addAll(s2) transforms s1 into the union of s1 and s2. (The union of two sets is the set
containing all of the elements contained in either set.)
s1.removeAll(s2) transforms s1 into the (asymmetric) set difference of s1 and s2. (For
example, the set difference of s1 minus s2 is the set containing all of the elements found in s1 but
not in s2.)
To calculate the union, intersection, or set difference of two sets nondestructively (without modifying either
set), the caller must copy one set before calling the appropriate bulk operation. The following are the
resulting idioms.
import java.util.*;
public class FindDups2 {
public static void main(String[] args) {
Set<String> uniques = new HashSet<String>();
Set<String> dups
= new HashSet<String>();
for (String a : args)
if (!uniques.add(a))
dups.add(a);
// Destructive set-difference
uniques.removeAll(dups);
}
}
System.out.println("Unique words:
" + uniques);
System.out.println("Duplicate words: " + dups);
When run with the same argument list used earlier ( icameisawileft), the program yields the
following output.
Unique words:
[left, saw, came]
Duplicate words: [i]
A less common set-algebraic operation is the sym