How to sort HashSet in Java? Example

Somebody asked me recently, how do you sort a HashSet? For lists, we use the Collections.sort(List) method, but there is nothing for Set. If I have a HashSet then how would I go about sorting it? The answer is you cannot sort a HashSet, why? because HashSet is an unordered collection. When you insert an element in HashSet then you lose the order guarantee. You cannot do reordering or sorting in Set because it does not have random access methods (ie, .get() an element at a given index), which is basically required for sort algorithms.

Though you can sort the HashSet by first converting HashSet to List and then sorting it. Also, some of the Set implementations may keep the order intact e.g. LinkedHashSet maintains insertion order, which means you can sort LinkedHashSet but not HashSet. Alternatively, you can also use TreeSet to keep elements in sorted order from the start.

In short, you cannot sort HashSet directly but you can do so by converting it into a List and then sorting a List and accessing elements from it in sorted order for further processing. 

If you are new to Java and want to learn the Java Collection framework in deep, then you can also these Java Collection courses online, one of the best online courses to learn generics, Streams, and collection.




How to sort HashSet in Java? Example Tutorial 

Here is a simple Java program that attempts to sort a HashSet first by converting it into List and also by using TreeSet, which is your sorted set. I have first created a HashSet of String and stored a couple of names in arbitrary order. 

Later I have printed the HashSet to show that elements are not stored in any order. 

After that, we have converted our HashSet to ArrayList and sorted it using the Collections.sort() method. 

You can see elements in sorted order in our second print statement. But this is not the only way and you can also use TreeSet to sort HashSet elements as shown in the second example.

How to sort HashSet in Java




Java Program to sort HashSet using List and TreeSet

Here is our complete Java program to sort a HashSet in Java, while sorting HashSet doesn't make sense because it's not a data structure designed to keep elements in sorted order, for that you have a TreeSet which can store elements in their natural order or any custom order defined by Comparator interface in Java. 
package dto;

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

/**
 * Program to sort HashSet in Java using List and TreeSet
 * 
 * @author WINDOWS 8
 *
 */
public class HashSetSortingDemo{

    public static void main(String args[]) {

       HashSet<String> names = new HashSet<String>();
       
       names.add("Asker");
       names.add("Crak");
       names.add("Bayliss");
       names.add("Mohna");
       names.add("Dina");
       
       System.out.println("HashSet before sorting : " + names);
       
       
       // Sorting HashSet using List
       List<String> tempList = new ArrayList<String>(names);
       Collections.sort(tempList);
       
       System.out.println("HashSet element in sorted order : " + tempList);
       
       // Sorting HashSet using TreeSet
       TreeSet<String> sorted = new TreeSet<String>(names);
       
       System.out.println("HashSet sorted using TreeSet : " + sorted);
    }

}

Output :
HashSet before sorting : [Asker, Mohna, Bayliss, Dina, Crak]
HashSet element in sorted order : [Asker, Bayliss, Crak, Dina, Mohna]
HashSet sorted using TreeSet : [Asker, Bayliss, Crak, Dina, Mohna]


That's all about how to sort HashSet in Java. As I said, HashSet is an unordered collection, and it's not possible to store elements in any order, but if you have to access elements of HashSet in sorted order then you can first convert it to List and then sort it out, but that's not the only way. You can also use TreeSet to sort the HashSet in Java.

If you like this article and wants to know more about how to work with different Collection classes e.g. List, Set, Map or Queue, see the following tutorials :
  • What are the similarities and differences between HashSet and TreeSet in Java? (answer)
  • How HashSet internally works in Java? (answer)
  • Difference between HashSet and TreeSet in Java? (answer)
  • What is the difference between ArrayList and HashSet in Java? (answer)
  • How do you loop through HashSet in Java? (code)
  • How to sort an array using QuickSort Algorithm in Java? (solution)
  • How to sort an ArrayList in descending order in Java? (example)
  • How to sort objects in Java? (answer)
  • Difference between HashSet and HashMap in Java? (answer)
  • Difference between LinkedHashSet, TreeSet, and HashSet in Java? (answer)
  • How to sort HashMap by values in Java? (code)
  • Bubble sort algorithm in Java (implementation)
  • How to sort List in increasing order in Java? (answer)
  • 4 ways to sort an Array in Java? (program)
  • 2 ways to sort a HashMap in Java? (solution)
  • How insertion sort algorithm works in Java? (answer)
Thank you for reading this HashSet example so far. If you find the HashSet sorting example in Java useful then please share it with your friends and colleagues on social media. 

And lastly one question for you? What is difference between HashSet, LinkedHashSet, and TreeSet in Java? This one is a popular Java interview question and its worth know about it if you don't know already. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.