import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
public class TriHashSet {
public static void main(String[] args) {
//create a hashset
HashSet< String> hset = new HashSet< String> ();
//add elements
hset.add("a2");
hset.add("a3");
hset.add("b1");
hset.add("b3");
hset.add("a1");
hset.add("b2");
System.out.println("Before Sorting:");
for(String s: hset)
System.out.println(s);
//copy HashSet elements to ArrayList
List< String> list = new ArrayList< String> (hset);
Collections.sort(list);
System.out.println("After sorting:");
for(String s: hset)
System.out.println(s);
}
}
Before sorting:
b1
a1
b3
b2
a2
a3
After sorting:
b1
a1
b3
b2
a2
a3
import java.util.HashSet as an argument;Output:
import java.util.TreeSet;
public class TriHashSetTreeMap {
public static void main(String[] args) {
//create a hashset
HashSethset = new HashSet ();
//add elements
hset.add(5);
hset.add(16);
hset.add(8);
hset.add(22);
hset.add(14);
hset.add(11);
System.out.println("Before sorting: "+hset);
for(int n: hset)
System.out.println(n);
//copy HashSet elements into ArrayList
TreeSettreeset = new TreeSet< > (hset);
System.out.println("After sorting: "+treeset);
for(int n : treeset)
System.out.println(n);
}
}
Before sorting: [16, 5, 22, 8, 11, 14]
16
5
22
8
11
14
After IR: [5, 8, 11, 14, 16, 22]
5
8
11
14
16
22
Please disable your ad blocker and refresh the window to use this website.