How to Sort HashSet in Java

This post shows how to sort a HashSet in Java. Since HashSet is an unordered collection so you will need to convert it to another collection in order to sort a HashSet. There are two options to sort a HashSet by converting it to another collection.

  1. Convert HashSet to list and use Collections.sort() method where you can pass List as an argument.
  2. Convert HashSet to TreeSet by using constructor of the TreeSet class. Since TreeSet is a NavigableSet implementation. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

Sorting HashSet using Collections.sort() method

If you are sorting HashSet in Java using this way you need to convert HashSet to List and pass it to Collections.sort() method which will sort is as per natural ordering.
If you want to sort it in different order you can use a Comparator.

Refer How to Sort ArrayList in Java to see sorting of the List by passing a Comparator.

Drawback of using this option is that it returns a list.


Sorting HashSet by converting to TreeSet

If you want to sort HashSet in Java using this way you just need to pass your HashSet to a constructor of TreeSet, it will be sorted in its natural order. If you use this way to sort a HashSet you will still have a Set not a List after sorting as was the case with previous option.


That’s all for the topic How to Sort HashSet in Java. If something is missing or you have something to share about the topic please write a comment.

You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.