There may be a situation when you want to sort a HashSet in Java. Since the very idea of HashSet is to store elements according to the calculated Hash so by design HashSet is unordered. Thus, in order to sort a HashSet you can either-
- Convert HashSet to a list and then sort that List by using Collections.sort() method. One drawback of using this option to sort a HashSet is that you get the result as list.
- Create a TreeSet by passing the HashSet, it will automatically be sorted. TreeSet is an implementation of SortedSet and stores its element in sorted order. This option gives the result as Set.
Let's see a Java program where a HashSet storing strings is sorted.
Java Program to sort a HashSet
public class SetSorting { public static void main(String[] args){ Set<String> citySet = new HashSet<String>(); citySet.add("Delhi"); citySet.add("Mumbai"); citySet.add("Bangalore"); citySet.add("Chennai"); citySet.add("Hyderabad"); //Convert it to a list and sort List<String> cityList = new ArrayList<>(citySet); Collections.sort(cityList); System.out.println("Sorted List " + cityList); // Sorting HashSet by using treeset Set<String> sortedSet = new TreeSet<String>(citySet); System.out.println("Sorting set by converting it to TreeSet " + sortedSet); // By using Java 8 stream and sorting Set<String> ab = citySet.stream().collect(Collectors.toCollection(TreeSet::new)); System.out.println("SOrted Set using Java 8 Stream " + ab); } }
Output
Sorted List [Bangalore, Chennai, Delhi, Hyderabad, Mumbai] Sorting set by converting it to TreeSet [Bangalore, Chennai, Delhi, Hyderabad, Mumbai] SOrted Set using Java 8 Stream [Bangalore, Chennai, Delhi, Hyderabad, Mumbai]
Here first way to sort HashSet is to convert HashSet into a List and then sort that list. If you are ok with having a sorted elements in a list then this way is just fine. But don't do the mistake of converting it back to HashSet as shown below because converting back to HashSet will again make it unordered.
citySet = new HashSet<String>(cityList); System.out.println("" + citySet);
While sorting a HashSet using a TreeSet, if you want another ordering than the natural ordering then you'll have to provide a comparator with the treeset.
- Refer How to Sort elements in different order in TreeSet to know more about how to sort TreeSet in different order.
From Java 8 onwards sorting the HashSet using a TreeSet can be done using collect() operation in stream API. It is still creating a TreeSet using the given HashSet but method reference is used here to create a new TreeSet.
- Refer Method reference in Java 8 to know more about Method reference.
That's all for this topic How to Sort HashSet in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment