|
| 1 | +/******************************************************************************* |
| 2 | +* (Perform set operations on hash sets) Create two linked hash sets {"George", * |
| 3 | +* "Jim", "John", "Blake", "Kevin", "Michael"} and {"George", "Katie", "Kevin", * |
| 4 | +* "Michelle", "Ryan"} and find their union, difference, and intersection. * |
| 5 | +* (You can clone the sets to preserve the original sets from being changed by * |
| 6 | +* these set methods.) * |
| 7 | +*******************************************************************************/ |
| 8 | +importjava.util.*; |
| 9 | + |
| 10 | +publicclassExercise_21_01 { |
| 11 | +publicstaticvoidmain(String[]args) { |
| 12 | +// Create two linked hash sets |
| 13 | +Set<String>set1 =newLinkedHashSet<>(Arrays.asList( |
| 14 | +"George","Jim","John","Blake","Kevin","Michael")); |
| 15 | +Set<String>set2 =newLinkedHashSet<>(Arrays.asList( |
| 16 | +"George","Katie","Kevin","Michelle","Ryan")); |
| 17 | + |
| 18 | +// Display the union of the two sets |
| 19 | +Set<String>union =newLinkedHashSet<>(set1); |
| 20 | +union.addAll(set2); |
| 21 | +System.out.println("Union of the two sets: " +union); |
| 22 | + |
| 23 | +// Display the difference of the two sets |
| 24 | +Set<String>difference =newLinkedHashSet<>(set1); |
| 25 | +difference.removeAll(set2); |
| 26 | +System.out.println("Difference of the two sets: " +difference); |
| 27 | + |
| 28 | + |
| 29 | +// Display the intersetion of the two sets |
| 30 | +Set<String>intersection =newLinkedHashSet<>(); |
| 31 | +for (Stringe:set2) { |
| 32 | +if (set1.contains(e)) |
| 33 | +intersection.add(e); |
| 34 | +} |
| 35 | +System.out.println("Intersection of the two sets: " +intersection); |
| 36 | +} |
| 37 | +} |