-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetExamples.java
More file actions
37 lines (33 loc) · 1.27 KB
/
SetExamples.java
File metadata and controls
37 lines (33 loc) · 1.27 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
import java.util.HashSet;
import java.util.TreeSet;
public class SetExamples {
public static void main(String[] args) {
// Demonstrating the use of HashSet
System.out.println("HashSet Example:");
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
hashSet.add("Apple"); // Duplicate entry, will not be added
// Displaying the elements of HashSet
for (String fruit : hashSet) {
System.out.println(fruit);
}
// Demonstrating the use of TreeSet
System.out.println("\nTreeSet Example:");
TreeSet<Integer> treeSet = new TreeSet<>();
treeSet.add(5);
treeSet.add(3);
treeSet.add(8);
treeSet.add(1);
// Displaying the elements of TreeSet (sorted order)
for (Integer number : treeSet) {
System.out.println(number);
}
// Demonstrating the unique properties of sets
System.out.println("\nSet Properties:");
System.out.println("Size of HashSet: " + hashSet.size());
System.out.println("Contains 'Banana': " + hashSet.contains("Banana"));
System.out.println("Contains 'Grapes': " + hashSet.contains("Grapes"));
}
}