Signup/Sign In

How to sort HashSet Elements in Java

In this post, we are going to sort HashSet elements in Java. HashSet is an implementation class of Set interface in Java that is used to store data but does not maintain any order.

To sort and HashSet there are several methods like convert HashSet to TreeSet or sort() method of Collections class or using sorted() method of the stream.

Since HashSet does not guarantee insertion order and does not store elements in sorting order then Java provides TreeSet to store sorted data.

Time for an Example:

Let's create an example to get HashSet elements sorted. Here, we are converting HashSet elements to TreeSet that stores elements in sorted order.

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

public class Main {
	public static void main(String[] args){
		Set<Integer> set = new HashSet<>();
		set.add(14);
		set.add(20);
		set.add(50);
		set.add(10);
		System.out.println(set);
		// Sorting
		set = new TreeSet<>(set);
		System.out.println(set);		
	}
}


[50, 20, 10, 14]
[10, 14, 20, 50]

Example 1

Let's create another example of sort the HashSet elements. Here, we are using the sort() method of the Collections class that returns a list of sorted elements. This example is useful when you want to get sorted elements no matter it is set or a list.

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

public class Main {
	public static void main(String[] args){
		Set<Integer> set = new HashSet<>();
		set.add(14);
		set.add(20);
		set.add(50);
		set.add(10);
		System.out.println(set);
		// Sorting
		List<Integer> list = new ArrayList<>(set);
		Collections.sort(list);
		System.out.println(list);		
	}
}


[50, 20, 10, 14]
[10, 14, 20, 50]

Example 2

If you are using Java 8 or higher Java version then you can use Stream API and its method sorted() that sort the stream elements and toList() method returns the list of these elements. See the example below.

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Main {
	public static void main(String[] args){
		Set<Integer> set = new HashSet<>();
		set.add(14);
		set.add(20);
		set.add(50);
		set.add(10);
		System.out.println(set);
		// Sorting
		List<Integer> list = set.stream()
		  .sorted()
		  .collect(Collectors.toList()); 
		System.out.println(list);
	}
}


[50, 20, 10, 14]
[10, 14, 20, 50]



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.