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}
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