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
you can do this in the following ways:
Method 1:
Method 2:
Method 2 is more preferable because the other method consumes lot of time to transfer data back and forth between hashset and list.
Java 8 way to sort it would be:
*
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 withList<Foo> sortedListOfFoo =
In my humble opinion , LazerBanana's answer should be the top rated answer & accepted because all the other answers pointing to
java.util.TreeSet
( or first convert to list then callCollections.sort(...)
on the converted list ) didn't bothered to ask OP as what kind of objects yourHashSet
has i.e. if those elements have a predefined natural ordering or not & that is not optional question but a mandatory question.You just can't go in & start putting your
HashSet
elements into aTreeSet
if element type doesn't already implementComparable
interface or if you are not explicitly passingComparator
toTreeSet
constructor.From
TreeSet
JavaDoc ,That is why only all Java8 stream based answers - where you define your comparator on the spot - only make sense because implementing comparable in POJO becomes optional. Programmer defines comparator as and when needed. Trying to collect into
TreeSet
without asking this fundamental question is also incorrect ( Ninja's answer). Assuming object types to beString
orInteger
is also incorrect.Having said that, other concerns like ,
should be the other relevant points too. Just pointing to API shouldn't be only intention.
Since Original set already contains only unique elements & that constraint is also maintained by sorted set so original set needs to be cleared from memory since data is duplicated.
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 has function with more than likely is not lexographic.You can use a TreeSet instead.