How to Sort HashSet in Java

Previous
Next

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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog