I need to sort a Set of String's which holds number.Ex: [15, 13, 14, 11, 12, 3, 2, 1, 10, 7, 6, 5, 4, 9, 8]
. I need to sort it to [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
. But when i use Collections.sort(keyList);
where keyList is Set, the reult i obtained is [1, 10, 11, 12, 13, 14, 15, 2, 3, 4, 5, 6, 7, 8, 9]
. Please help.
相关问题
- 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
Your Strings will be sorted as Strings in natural order, and not as numbers. So,
"11"
comes after"10"
and"2"
will come after"11111111110"
.What to do?.
Use
Integer.parseInt()
to parse each String value in the set as integer, then add them to a set and callCollections.sort()
.can you try with:
The result is:
The list needs to be
int
Transform the
String
s intoInteger
s first.If you don't require duplicate values, you can use a
SortedSet
, which maintains the order automatically:Write a custom comparator and parse it as argument to
Collections.sort(Collection,Comparator)
. One solution is parsing your Strings to Integers.you could do as Kai said, and convert your String to integer and compare it
but it is expensive operation,what i suggest is this :
if your numbers has same length, then compare them by using
String.compareTo
, otherwise, sort them by order, so 1 2 3 will be automatically before 11 22 etc