For lists, we use the Collections.sort(List)
method. What if we want to sort a HashSet
?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- How to toggle on Order in ReactJS
- StackExchange API - Deserialize Date in JSON Respo
We can not decide that the elements of a HashSet would be sorted automatically. But we can sort them by converting into TreeSet or any List like ArrayList or LinkedList etc.
You can use guava library for the same
This simple command did the trick for me:
I used this within a print statement, so if you need to actually persist the ordering, you may need to use TreeSets or other structures proposed on this thread.
Add all your objects to the
TreeSet
, you will get a sorted Set. Below is a raw example.Elements in HashSet can't be sorted. Whenever you put element into HashSet, it will mess up the whole buckets. The good thing about it is efficiency in performance.
TreeSet will sort all the elements automatically every time you insert an element.
Perhaps, what you are trying to do is to sort just once. In that case, TreeSet is not the best option because it needs to determine the placing of new added elements all the time.
The most efficient solution is to use ArrayList. Create a new list and add all the elements then sort it once. If you want to retain only unique elements (remove all duplicates like set does, then put the list into a LinkedHashSet, it will retain the order you have already sorted)
Now, you've gotten a sorted set if you want it in a list form then convert it into list.
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: