How to sort a HashSet? How to sort a HashSet? java java

How to sort a HashSet?


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);


Add all your objects to the TreeSet, you will get a sorted Set. Below is a raw example.

HashSet myHashSet = new HashSet();myHashSet.add(1);myHashSet.add(23);myHashSet.add(45);myHashSet.add(12);TreeSet myTreeSet = new TreeSet();myTreeSet.addAll(myHashSet);System.out.println(myTreeSet); // Prints [1, 12, 23, 45]

Update

You can also use TreeSet's constructor that takes a HashSet as a parameter.

HashSet myHashSet = new HashSet();myHashSet.add(1);myHashSet.add(23);myHashSet.add(45);myHashSet.add(12);TreeSet myTreeSet = new TreeSet(myHashSet);System.out.println(myTreeSet); // Prints [1, 12, 23, 45]

Thanks @mounika for the update.


Java 8 way to sort it would be:

fooHashSet.stream()  .sorted(Comparator.comparing(Foo::getSize)) //comparator - how you want to sort it  .collect(Collectors.toList()); //collector - what you want to collect it to

*Foo::getSize it's an example how to sort the HashSet of YourItem's naturally by size.

*Collectors.toList() is going to collect the result of sorting into a List the you will need to capture it with List<Foo> sortedListOfFoo =