开发者

Why 10 in the beginning of an ArrayList after Sort()

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, Integers or Doubles) instead of strings.


If the list needs to be of Strings 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.


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.


Lexicographic order of sequences.


I couldn't understand it because I was creating integers and not strings, but it didn't work.

But then I saw a little mistake in my code I forgot the Integer.parseint(String) which was commented out.

The answers guys were helpful anyway, and loads of other ways to approach this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜