Java stream sorting a List of String as numbers problem

Hoang Nguyen :

I have an issue sorting a list of QuestionNumbers as Strings.

List<String> list = Arrays.asList("12.2", "12.1", "12.3", "12.4", "12.5", "12.10");

List<String> sortedList = list.stream().sorted().collect(Collectors.toList());

When printed out sortedList I get:

12.1
12.10
12.2
12.3
12.4
12.5

I tried the following but getting a multi points errors. Please help

.sorted(Comparator.comparingDouble(question ->(Double.parseDouble(question.getQuestionNumber()))  ))
lczapski :

As it was written in comments: you can combine two Comparator first is by length, then by String value.

list.stream()
    .sorted(Comparator
            .comparing(String::length)
            .thenComparing(String::compareTo))
    .collect(Collectors.toList());

UPDATE

As it was written by Holger there are some problems with above approach. It can be rewrite as below:

list.stream()
    .sorted(Comparator.comparing((String s) -> s.split("\\."),
        Comparator
            .comparing((String[] a) -> Integer.parseInt(a[0]))
            .thenComparingInt((a) -> a.length > 1 ? Integer.parseInt(a[1]) : 0))
    )
    .collect(Collectors.toList());

But it looks more complicated and it's doing more or less the same what was proposed by VGR. So in the end you can write it like this:

list.stream()
    .sorted(Comparator.comparing(Runtime.Version::parse))
    .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11683&siteId=1