Monday, 2 November 2015

How to sort HashSet in Java

There may be a situation when you want to sort a HashSet in Java. Since the very idea of HashSet is to store elements according to the calculated Hash so by design HashSet is unordered. Thus, in order to sort a HashSet we can either convert it to a list (if you are ok with a result as list), or use a TreeSet which is an implementation of SortedSet.

Let's see a Java program where a set storing strings is sorted.

Java Program

  public class SetSorting {

    public static void main(String[] args){
        Set<String> citySet = new HashSet<String>();
        //Convert it to a list and sort
        List<String> cityList = new ArrayList<>(citySet);
        System.out.println("Sorted List " + cityList);
        /*citySet = new HashSet<String>(cityList);
        System.out.println("" + citySet);*/
        // By using treeset
        Set<String> sortedSet = new TreeSet<String>(citySet);
        System.out.println("Sorting set by converting it to TreeSet " + sortedSet);
        // By using Java 8 stream and sorting
        Set<String> ab =;
        System.out.println("SOrted Set using Java 8 Stream " + ab);


Sorted List [Bangalore, Chennai, Delhi, Hyderabad, Mumbai]
Sorting set by converting it to TreeSet [Bangalore, Chennai, Delhi, Hyderabad, Mumbai]
SOrted Set using Java 8 Stream [Bangalore, Chennai, Delhi, Hyderabad, Mumbai]

Here first way is to convert HashSet into a List and then sort that list. If you are ok with having a sorted elements in a list then this way is just fine. But don't do the mistake of converting it back to HashSet, like this

 citySet = new HashSet<String>(cityList);
 System.out.println("" + citySet);
As converting back to HashSet will again make it unordered.

Second way is to create a TreeSet from the given HashSet it will automatically be sorted. So in just one line you have a sortedset.

Note that if you want another ordering than the natural ordering then you'll have to provide a comparator with the treeset.

Again in Java 8 same thing can be done using collect() operation in stream API. It is still creating a TreeSet using the given HashSet. Here new TreeSet is created using the method reference.

That's all for this topic How to sort HashSet in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

Related Topics

  1. How HashSet works internally in Java
  2. LinkedHashSet in Java
  3. How to sort arraylist of custom objects in Java
  4. Difference between Comparable and Comparator
  5. Java Collections interview questions

You may also like -

No comments:

Post a Comment