1//Creating HashSet
2HashSet<String> set = new HashSet();
3
4//adding elements
5set.add("One");
6set.add("Two");
7
8//Removing element);
9set.remove("One");
10
11//Removing all the elements available in the set
12set.clear();
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.
1import java.util.Arrays;
2import java.util.HashSet;
3import java.util.Set;
4/*
5check a set size by set.size()
6*/
7
8public class MainClass {
9 public static void main(String[] a) {
10 String elements[] = { "A", "B", "C", "D", "E" };
11 Set set = new HashSet(Arrays.asList(elements));
12
13 System.out.println(set.size());
14 }
15}
16
1s1.containsAll(s2) — returns true if s2 is a subset of s1. (s2 is a subset of s1 if set s1 contains all of the elements in s2.)
2s1.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.)
3s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements common to both sets.)
4s1.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.)