Hi All,

Greetings on the day!

Today we will see how we can sort HashSet in both ascending & descending order, also we will learn how we can sort HashSet using java 8.

So let's start.

We can sort HashSet using TreeSet & ArrayList. TreeSet will automatically order data in ascending order.

 If we want to use ArrayList we need to follow the below 3 steps.

  • Convert Set to ArrayList
  • Sort List
  • Convert list to set

So let's see the example of that.

O/P

Sorted in ascending order using TreeSet [Ankit, Bhavesh, Pratik, Rajesh]

Sorted in ascending order using ArrayList [Ankit, Bhavesh, Pratik, Rajesh]

Sorted in descending order using ArrayList [Rajesh, Pratik, Bhavesh, Ankit] 

Now let's see how to sort HashSet in ascending & descending order using java 8 streams.

O/P

Hope you have a good learning experience. If you have any questions let me know.

You can refer to the related post.

Java Interview Programs - Count No Of Occurrences Of Element In List + Find Duplicate Elements In List + Java 8

Sorting HashMap By Key And Value + Java 8

Sorting Array List In Ascending & Descending Order + Java 8 + Sorting Array List Of Custom Object

Comparator and Comparable In Java + Difference Between Comparator and Comparable + Java 8

Java 8 Stream - Intermediate Operations With Examples

Java 8 Stream - Terminal Operations With Examples

For Spring visit Spring Tutorial

Thanks

Happy Learning!