1import java.util.*;
2public class SetDemo {
3
4 public static void main(String args[]) {
5 int count[] = {34, 22,10,60,30,22};
6 Set<Integer> set = new HashSet<Integer>();
7 try {
8 for(int i = 0; i < 5; i++) {
9 set.add(count[i]);
10 }
11 System.out.println(set);
12
13 TreeSet sortedSet = new TreeSet<Integer>(set);
14 System.out.println("The sorted list is:");
15 System.out.println(sortedSet);
16
17 System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
18 System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
19 }
20 catch(Exception e) {}
21 }
22}
23
24OUTPUT:
25
26 [34, 22, 10, 60, 30]
27 The sorted list is:
28 [10, 22, 30, 34, 60]
29 The First element of the set is: 10
30 The last element of the set is: 60
1import java.util.*;
2public class SetDemo {
3
4 public static void main(String args[]) {
5 int count[] = {34, 22,10,60,30,22};
6 Set<Integer> set = new HashSet<Integer>();
7 try {
8 for(int i = 0; i < 5; i++) {
9 set.add(count[i]);
10 }
11 System.out.println(set);
12
13 TreeSet sortedSet = new TreeSet<Integer>(set);
14 System.out.println("The sorted list is:");
15 System.out.println(sortedSet);
16
17 System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
18 System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
19 }
20 catch(Exception e) {}
21 }
22}
1A Set is a Collection that cannot contain duplicate elements.
2
3The Set interface contains only methods inherited from Collection
4and adds the restriction that duplicate elements are prohibited.
1
2SET: Can only store unique values,
3 And does not maintain order
4- HashSet can have null, order is not guaranteed
5- LinkedHashSet can have null and keeps the order
6- TreeSet sorts the order and don't accept null
7
8