How to sort a HashSet?

Diana picture Diana · Mar 13, 2014 · Viewed 248.6k times · Source

For lists, we use the Collections.sort(List) method. What if we want to sort a HashSet?

Answer

isak gilbert picture isak gilbert · Mar 13, 2014

A HashSet does not guarantee any order of its elements. If you need this guarantee, consider using a TreeSet to hold your elements.

However if you just need your elements sorted for this one occurrence, then just temporarily create a List and sort that:

Set<?> yourHashSet = new HashSet<>();

...

List<?> sortedList = new ArrayList<>(yourHashSet);
Collections.sort(sortedList);