-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path5. HashSets and Sets
More file actions
78 lines (53 loc) · 2.08 KB
/
5. HashSets and Sets
File metadata and controls
78 lines (53 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class App {
public static void main(String[] args) {
// HashSet does not retain order.
// Set<String> set1 = new HashSet<String>();
// LinkedHashSet remembers the order you added items in
// Set<String> set1 = new LinkedHashSet<String>();
// TreeSet sorts in natural order
Set<String> set1 = new TreeSet<String>();
if (set1.isEmpty()) {
System.out.println("Set is empty at start");
}
set1.add("dog");
set1.add("cat");
set1.add("mouse");
set1.add("snake");
set1.add("bear");
if (set1.isEmpty()) {
System.out.println("Set is empty after adding (no!)");
}
// Adding duplicate items does nothing.
set1.add("mouse");
System.out.println(set1);
// ///////// Iteration ////////////////
for (String element : set1) {
System.out.println(element);
}
// ////////// Does set contains a given item? //////////
if (set1.contains("aardvark")) {
System.out.println("Contains aardvark");
}
if (set1.contains("cat")) {
System.out.println("Contains cat");
}
/// set2 contains some common elements with set1, and some new
Set<String> set2 = new TreeSet<String>();
set2.add("dog");
set2.add("cat");
set2.add("giraffe");
set2.add("monkey");
set2.add("ant");
////////////// Intersection ///////////////////
Set<String> intersection = new HashSet<String>(set1);
intersection.retainAll(set2);
System.out.println(intersection);
////////////// Difference /////////////////////////
Set<String> difference = new HashSet<String>(set2);
difference.removeAll(set1);
System.out.println(difference);
}
}