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.
-
2String comparisons are alphabetic. Try to convert it to an Integer list to get the desired result.blackSmith– blackSmith2014-09-19 12:28:30 +00:00Commented Sep 19, 2014 at 12:28
-
Please post the actual code that you used.wei2912– wei29122014-09-19 12:28:43 +00:00Commented Sep 19, 2014 at 12:28
-
2Collections.sort accepts a Comparator as an argument. This enables you to define the compare function yourself. (Effectively, modify to int and then compare the values)Ronald– Ronald2014-09-19 12:30:51 +00:00Commented Sep 19, 2014 at 12:30
6 Answers
Write a custom comparator and parse it as argument to Collections.sort(Collection,Comparator). One solution is parsing your Strings to Integers.
Collections.sort(keyList, new Comparator<String>()
{
@Override
public int compare(String s1, String s2)
{
Integer val1 = Integer.parseInt(s1);
Integer val2 = Integer.parseInt(s2);
return val1.compareTo(val2);
}
});
Comments
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 :
keyList.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() == o2.length()){
return o1.compareTo(o2);
}
return o1.length() - o2.length();
}
});
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
Comments
Transform the Strings into Integers first.
List<Integer> ints = new ArrayList<>();
for (String s : strings)
ints.add(Integer.parseInt(s));
Collections.sort(ints);
If you don't require duplicate values, you can use a SortedSet, which maintains the order automatically:
SortedSet<Integer> ints = new TreeSet<>();
for (String s : strings)
ints.add(Integer.parseInt(s));
// all done!
Comments
Strings in Java are ordered lexicographically, comparing each character in order. Since '1' < '2', the string "12" is less than the string "2", since the first character of "12" is less than the first character of "2".
You can use a custom comparator to compare the numerical value of strings, rather than using their natural order:
Collections.sort(keyList, Comparator.comparing(Integer::parseInt));