Issue with Sort native method Java

Viewed 141

I'm trying to order elements using native sort method.

Code:

List<String> list = new ArrayList();
Collections.sort(list);

Input 1:

Before order: 65 31 37 37 72 76 61 35 57 37
After order:  31 35 37 37 37 57 61 65 72 76
Expected:     Ok.

Input 2:

Before order: 45 186 185 55 51 51 22 78 64 26 49 21
After order:  185 186 21 22 26 45 49 51 51 55 64 78
Expected:     21 22 26 45 49 51 51 55 64 78 185 186

The problem is that the method is sorting wrong in some cases, how can I solve it?

3 Answers

You should sort by

  1. integer value of string

That is

Collections.sort(list,
    Comparator.comparing(Integer::parseInt));

Or sort by

  1. length of string
  2. string itself

That is

Collections.sort(list,
    Comparator.comparing(String::length)
              .thenComparing(Function.identity()));
Related