Why 10 at the beginning of ArrayList after Sort ()

As stated in this question, I have this problem. I know why this is at the beginning, because it is 1 and 0, so its up to 9 even after sorting. But can it be in the correct order using sort()list methods ?

+3
source share
8 answers

You need to change your list to use numbers (for example, Integeror Doubles) instead of numbers .

+12
source

If for some reason the list should be String(it seems unlikely to me), one option (using Guava ):

List<String> numbers = ...;
Collections.sort(numbers, Ordering.natural().onResultOf(
    new Function<String, Integer>() {
      public Integer apply(String from) {
        return Integer.valueOf(from);
      }
    }));

, . , .

+3

:

Comparator<String> , String Number . , .

+1

, :

    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));

JUnit.

0

, , . , , , Apache Commons Collection Utils ComparatorUtils.NATURAL_COMPARATOR, .

0

Java String , . . Java Trail . , - .. List<String> List<Integer> List<Double>, , .

However, this question in Stackoverflow may help you.

0
source

I could not figure it out because I was creating integers, not strings, but that didn't work.

But then I saw a small error in my code, I forgot Integer.parseint(String), which was commented on.

Answers guys were helpful anyway, and many other ways to get close to this.

0
source

Lexicographic sequence order.

0
source

Source: https://habr.com/ru/post/1762501/


All Articles