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.
- Looking for ⚒️ tech jobs? Go to our job portal.
- Looking for tech events? Go to tech events 🗓️ Calendar.️
Using TreeSet
You can use TreeSet to sort HashSet. As you know that TreeSet stores objects in ascending order by default.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
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: |
Using Collections’s sort
You can convert HashSet to List and then use Collections’s sort method to sort the HashSet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
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:
[Steve, John, Martin, Andy, Mary] ==================================
After Sorting:
[Andy, John, Martin, Mary, Steve]
That’s all about how to sort HashSet in java.