Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use thenComparing in java stream

I have a map with strings as values. I want to sort it firstly by length, and if length of the strings is the same, i want to sort it alphabetic. I wrote those code :

String out = outMap.values().stream()
                .sorted(Comparator.comparing(e -> e.length()).thenComparing()...)
                .collect(Collectors.joining());

The problem is, when i am writing thenComparing, I couldn't use e.length() anymore. How can i fix it?

EDIT : Map<Character, String> . I want to sort the strings and make one string in output by concat all of them.

like image 896
Anton Barinov Avatar asked Sep 25 '26 02:09

Anton Barinov


1 Answers

How about

String out = outMap.values().stream()
        .sorted(Comparator.comparingInt(String::length)
                          .thenComparing(Comparator.naturalOrder()))
                    //OR  .thenComparing(String.CASE_INSENSITIVE_ORDER))
        .collect(Collectors.joining());
like image 153
Pshemo Avatar answered Sep 27 '26 17:09

Pshemo