How to sort a HashSet?

322,179

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

Share:
322,179
Diana
Author by

Diana

java programmer

Updated on October 26, 2021

Comments

  • Diana
    Diana over 2 years

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

    • Alexis C.
      Alexis C. over 10 years
      A HashSet is an unordered collection.
    • fge
      fge over 10 years
      You 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
      demongolem over 10 years
      You could convert it to a list first then sort if you need to sort
    • user207421
      user207421 about 8 years
      You can't since a HashSet doesn't have a defined order. Your question embodies a contradiction in terms.
    • Tendai
      Tendai over 5 years
      use a TreeSet and if you can't control the source see the conversion an usage here stackoverflow.com/a/52987487/5153955
    • fatimasajjad
      fatimasajjad over 4 years
      The following answer can be very helpful for you stackoverflow.com/a/59964344/7397820
  • Sotirios Delimanolis
    Sotirios Delimanolis over 10 years
    Why are you assuming they store String values?
  • P45 Imminent
    P45 Imminent over 10 years
    I'm not though perhaps my use of lexographic is imprecise ;-)
  • Sotirios Delimanolis
    Sotirios Delimanolis over 10 years
    It'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 provided Comparator.
  • P45 Imminent
    P45 Imminent over 10 years
    I've edited. Better do you think , or should I delete the answer?
  • Sotirios Delimanolis
    Sotirios Delimanolis over 10 years
    I would just quote the javadoc.
  • Luiggi Mendoza
    Luiggi Mendoza over 10 years
    In case you move a HashSet to TreeSet, your class must implement Comparable interface or provide a custom Comparator. Otherwise, since you cannot sort a HashSet, just convert it into a List and sort it.
  • Diana
    Diana over 10 years
    I guess,I can use TreeSet with the constructor- TreeSet(Comparator<? super E> comparator).
  • Thomas Eizinger
    Thomas Eizinger almost 9 years
    I don't see where HashSet or Set has a method toList.
  • Roberto
    Roberto about 8 years
    That looks like Scala to me, which unfortunately doesn't solve the problem in Java.
  • Onic Team
    Onic Team over 7 years
    toList method , How is possible ?
  • wisbucky
    wisbucky about 6 years
    Also, if you're using a collection of Strings, then List<String> sortedList = new ArrayList<String>(yourHashSet);
  • Mounika
    Mounika about 5 years
    By using TreeSet myTreeSet = new TreeSet(myHashSet); you can avoid adding all the elements to Treeset again.
  • Jess
    Jess over 4 years
    Can you please, Add the logic to sort it in a specific order ?
  • Jess
    Jess over 4 years
    Just putting the elements wont give the flexibility of sorting on any order with any element inside it. The above solution does.
  • LazerBanana
    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
    Jess over 4 years
    I meant, how to define the Ascending or Descending
  • devconsole
    devconsole over 4 years
    new TreeSet<>(hashSet) is more concise and probably more efficient.
  • Jaco-Ben Vosloo
    Jaco-Ben Vosloo almost 3 years
    Your 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
    off99555 almost 3 years
    @Jaco-BenVosloo Thanks. I've edited the answer to reflect your comment.
  • ScanQR
    ScanQR over 2 years
    This will remove duplicates as OP asking to sort HashSet and it may contain duplicate values.
  • Abdullah Khan
    Abdullah Khan over 2 years
    Hashset may contain duplicate values!! Really!??
  • ceklock
    ceklock about 2 years
    I got this error: The method sort(List<T>) in the type Collections is not applicable for the arguments (List<capture#2-of ?>)