Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a HashSet?

People also ask

How do you sort the elements of a set?

Create a list and store all the hashset values into it. sort the list using Collections. sort() Store the list back into LinkedHashSet as it preserves the insertion order.

Why is HashSet not sorted?

because HashSet is an unordered collection. When you insert an element in HashSet then you lose the order guarantee. You cannot do reordering or sorting in Set because it does not have random access methods (ie, . get() an element at a given index), which is basically required for sort algorithms.


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 =


You can use a TreeSet instead.


Use java.util.TreeSet as the actual object. When you iterate over this collection, the values come back in a well-defined order.

If you use java.util.HashSet then the order depends on an internal hash function which is almost certainly not lexicographic (based on content).