How to Sort HashSet in Java

In this post, we will see how to sort HashSet in java.

HashSet is a collection which does not store elements in any order. You might come across a situation where you need to sort HashSet.

There can be many ways to sort HashSet, we will see two methods here.


Using TreeSet

You can use TreeSet to sort HashSet. As you know that TreeSet stores objects in ascending order by default.

package org.arpit.java2blog;

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

public class SortHashSetMain {

    public static void main(String[] args) {

         // Creating a new HashSet
        Set<String> set = new HashSet<String>();
        set.add("John");
        set.add("Martin");
        set.add("Andy");
        set.add("Steve");
        set.add("Mary");

        System.out.println("Before Sorting:");
        System.out.println(set);
        /*
         * Use TreeSet to sort HashSet
         */
        TreeSet<String> sortedSet=new TreeSet<>(set);

        System.out.println("==================================");
        System.out.println("After Sorting:");
        System.out.println(sortedSet);

    }
}   
When you run above program, you will get below output:
Before Sorting: [Steve, John, Martin, Andy, Mary] ================================== After Sorting: [Andy, John, Martin, Mary, Steve]

Using Collections’s sort

You can convert HashSet to List and then use Collections’s sort method to sort the HashSet.

package org.arpit.java2blog;

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

public class SortHashSetMain {

    public static void main(String[] args) {

         // Creating a new HashSet
        Set<String> set = new HashSet<String>();
        set.add("John");
        set.add("Martin");
        set.add("Andy");
        set.add("Steve");
        set.add("Mary");

        System.out.println("Before Sorting:");
        System.out.println(set);
        /*Convert to list and then use sort method
         */
        List<String> nameList = new ArrayList<String>(set);
        Collections.sort(nameList);

        System.out.println("==================================");
        System.out.println("After Sorting:");
        System.out.println(nameList);

    }
}   

When you run above program, you will get below output:

Before Sorting:
[Steve, John, Martin, Andy, Mary]
==================================
After Sorting:
[Andy, John, Martin, Mary, Steve]

That’s all about how to sort HashSet in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.