How to sort HashSet in Java? Example

Somebody asked me recently, how do you sort an HashSet? For lists, we use the Collections.sort(List) method, but there is nothing for Set. If I have an HashSet then how would I go about sorting it? The answer is you cannot sort an HashSet, why? because HashSet is an unordered collection. When you insert an element in HashSet than 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 Set implementation 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 the sorted order from the start.

In short, you cannot sort HashSet directly but you can do so by converting it into List and then sorting a List and accessing elements from it in sorted order for further processing. If you are new in Java and wants to learn Java Collection framework in deep, then you can also check Java Generics and Collection book, one of the best on generics and collection.

How to sort HashSet in Java

Here is a simple Java program which 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 an HashSet of String and stored 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 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 second example .

How to sort HashSet in Java

Java Program to sort HashSet using List and TreeSet

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>();
       System.out.println("HashSet before sorting : " + names);
       // Sorting HashSet using List
       List<String> tempList = new ArrayList<String>(names);
       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 un-ordered collection and its not possible to store element 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.

Further Reading
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 following tutorials :
  • What are 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 difference between ArrayList and HashSet in Java? (answer)
  • How do you loop through HashSet in Java? (code)
  • How to sort 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 an HashMap in Java? (solution)
  • How insertion sort algorithm works in Java? (answer)

No comments:

Post a Comment