How to sort a HashSet?
Solution 1
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);
Solution 2
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.
Solution 3
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 =
Solution 4
You can use a TreeSet instead.
Solution 5
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).
Comments
-
Diana over 2 years
For lists, we use the
Collections.sort(List)
method. What if we want to sort aHashSet
?-
Alexis C. over 10 yearsA
HashSet
is an unordered collection. -
fge over 10 yearsYou can't, since a
Set
does not have random access methods (ie,.get()
an element at a given index), which is basically required for sort algorithms ;) -
demongolem over 10 yearsYou could convert it to a list first then sort if you need to sort
-
user207421 about 8 yearsYou can't since a
HashSet
doesn't have a defined order. Your question embodies a contradiction in terms. -
Tendai over 5 yearsuse a TreeSet and if you can't control the source see the conversion an usage here stackoverflow.com/a/52987487/5153955
-
fatimasajjad over 4 yearsThe following answer can be very helpful for you stackoverflow.com/a/59964344/7397820
-
-
Sotirios Delimanolis over 10 yearsWhy are you assuming they store
String
values? -
P45 Imminent over 10 yearsI'm not though perhaps my use of lexographic is imprecise ;-)
-
Sotirios Delimanolis over 10 yearsIt's very wrong. It doesn't store keys in lexographic (sp?) order. It either uses their natural ordering (which depends on
Comparable
interface which the keys implement) or uses the providedComparator
. -
P45 Imminent over 10 yearsI've edited. Better do you think , or should I delete the answer?
-
Sotirios Delimanolis over 10 yearsI would just quote the javadoc.
-
Luiggi Mendoza over 10 yearsIn case you move a
HashSet
toTreeSet
, your class must implementComparable
interface or provide a customComparator
. Otherwise, since you cannot sort aHashSet
, just convert it into aList
and sort it. -
Diana over 10 yearsI guess,I can use TreeSet with the constructor- TreeSet(Comparator<? super E> comparator).
-
Thomas Eizinger almost 9 yearsI don't see where HashSet or Set has a method
toList
. -
Roberto about 8 yearsThat looks like Scala to me, which unfortunately doesn't solve the problem in Java.
-
Onic Team over 7 yearstoList method , How is possible ?
-
wisbucky about 6 yearsAlso, if you're using a collection of Strings, then
List<String> sortedList = new ArrayList<String>(yourHashSet);
-
Mounika about 5 yearsBy using
TreeSet myTreeSet = new TreeSet(myHashSet);
you can avoid adding all the elements to Treeset again. -
Jess over 4 yearsCan you please, Add the logic to sort it in a specific order ?
-
Jess over 4 yearsJust putting the elements wont give the flexibility of sorting on any order with any element inside it. The above solution does.
-
LazerBanana over 4 years@Jess i dont know whats the specific order for you Jess, you can sort it as you desire using the comparator.
-
Jess over 4 yearsI meant, how to define the Ascending or Descending
-
devconsole over 4 years
new TreeSet<>(hashSet)
is more concise and probably more efficient. -
Jaco-Ben Vosloo almost 3 yearsYour statement "TreeSet will sort all the elements automatically every time you insert an element" is untrue. If you change the value used for comparing of an object in the list, and then add a new object it will be placed as if the object you changed has its original value. Thus only the new item gets placed in the list at the correct point assuming none of the elements changed their value used to sort the list.
-
off99555 almost 3 years@Jaco-BenVosloo Thanks. I've edited the answer to reflect your comment.
-
ScanQR over 2 yearsThis will remove duplicates as OP asking to sort HashSet and it may contain duplicate values.
-
Abdullah Khan over 2 yearsHashset may contain duplicate values!! Really!??
-
ceklock about 2 yearsI got this error: The method sort(List<T>) in the type Collections is not applicable for the arguments (List<capture#2-of ?>)