How to sort a HashSet in java

HashSet does not preserve the order of the elements, however you can convert HashSet and order the elements in ascending order with two methods: using the method Collections.sort() or by copying the elements into a TreeSet.

1) Sort HashSet with Collections.sort()

The method Collections.sort() allows you to sort collections of objects that implement the interface java.util.List. You should copy the HashSet elements into one of the collections: ArrayList, LinkedList, or Vector.  We're going to use the ArrayList class, which is the simplest.   Next, we call the method Collections.sort() on our ArrayList.

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);
}
}
Output:

Before sorting: 
b1
a1
b3
b2
a2
a3
After sorting:
b1
a1
b3
b2
a2
a3

1) Sort HashSet using TreeSet

Using TreeSet is very simple. Just create an instance of TreeSet with the HashSet.

import java.util.HashSet as an argument; 
import java.util.TreeSet;

public class TriHashSetTreeMap {

public static void main(String[] args) {
//create a hashset
HashSet hset = 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
TreeSet treeset = new TreeSet< > (hset);

System.out.println("After sorting: "+treeset);
for(int n : treeset)
System.out.println(n);
}
}
Output:

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