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.

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.

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.

Was this post helpful?

Leave a Reply

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