Master java skills

How to Sort a HashSet in Java

There is no direct of sorting a hash set in java. But there are indirect ways.

  1. As we know TreeSet maintains natural sorting order of elements. We can convert our hash set into a tree set in order to sort it.
  2. We can make a list from our set and then sort the list using Collections.sort() method. And again convert the list into set using LinkedHashSet so that sorted order is maintained.

Sort a hash set using a tree set

package com.javatrainingschool;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

public class HashSetSortingExample {
	
	public static void main(String[] args) {
		
		Set<Integer> set = new HashSet<Integer>();
		
		set.add(123);
		set.add(13);
		set.add(435);
		set.add(54);
		
		System.out.println("Before sorting : " + set);
		
		Set<Integer> sortedSet = new TreeSet<Integer>(set);
		
		System.out.println("After sorting : " + sortedSet);
	}
}
Output :
Before sorting : [435, 54, 123, 13]
After sorting : [13, 54, 123, 435]

Sort a hash set using list

package com.javatrainingschool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class HashSetSortingExample {
	
	public static void main(String[] args) {
		
		Set<Integer> set = new HashSet<Integer>();
		
		set.add(123);
		set.add(13);
		set.add(435);
		set.add(54);
		
		System.out.println("Before sorting : " + set);
		
		List<Integer> list = new ArrayList<Integer>(set);
		Collections.sort(list);
		
		Set<Integer> sortedSet = new LinkedHashSet<Integer>(list);
		
		System.out.println("After sorting : " + sortedSet);
	}
}
Output :

Before sorting : [435, 54, 123, 13]
After sorting : [13, 54, 123, 435]