As the question says i have this problem. I know why it is in the beginning, because it is a 1 and a 0, so therefore its before 9 even after sorting. But, can it be in the right order with the lists sort() method?
You need to change your list to contain numbers (eg, Integer
s or Double
s) instead of strings.
If you're sorting Strings instead of numbers, this code might help you to understand the difference:
ArrayList stringList = new ArrayList();
stringList.add("9");
stringList.add("10");
Collections.sort(stringList);
Assert.assertEquals("10", stringList.get(0));
ArrayList integerList = new ArrayList();
integerList.add(9);
integerList.add(10);
Collections.sort(integerList);
Assert.assertEquals(9, integerList.get(0));
Asserting with JUnit assertions.
As others have said, if you intend to sort actual numbers do not store them in strings. If you really want to sort strings containing numbers naturally, I prefer to use Apache Commons Collection Utils ComparatorUtils.NATURAL_COMPARATOR, although there are other options with varying configurability and functionality.
Java doesn't natively support natural sorting of String
objects the way you might need. See the Java Trail about this. The main reason being that it would be too complicated to do so because of many different languages, etc. Therefore, the previous answers regarding changing your List<String>
to a List<Integer>
or List<Double>
is perhaps a better idea.
However, this question on Stackoverflow might be of assistance to you.
If the list needs to be of String
s for some reason (seems unlikely to me), one option (using Guava) is:
List<String> numbers = ...;
Collections.sort(numbers, Ordering.natural().onResultOf(
new Function<String, Integer>() {
public Integer apply(String from) {
return Integer.valueOf(from);
}
}));
This sorts the list of strings based on the integer value each string represents. If not every string can be parsed as an integer, an exception will be thrown.
One more suggestion:
You may implement a Comparator<String>
to support the sort algorithm if you need to stick to String and don't want to use Number or equivalent classes. This way you can sort the elements as needed.
Ahhh :)
I couldnt understand it because i was making Integers and not strings, but it didnt work anyway. But then i saw a little mistake in my code :P i forgot the Integer.parseint(String) :) it was commented out...
Thx for the answers guys :) it was helpful anyway, and loads of other ways to do it :) thank you