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.

  • What are the types of outMap?– BohemianFeb 14 at 21:04
  • fix what? what exactly is the problem?– EugeneFeb 14 at 21:05
  • Map<Character, String>– Anton BarinovFeb 14 at 21:08

How about

String out=outMap.values().stream().sorted(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder())).collect(Collectors.joining());
  • 1
    Alternatively, (String e) -> e.length().– shmoselFeb 14 at 21:06
  • 2
    Comparator.comparingInt(String::length) .thenComparing(String.CASE_INSENSITIVE_ORDER); just in case.– boobalanFeb 14 at 21:08
  • Yes, that works fine, thanks a lot– Anton BarinovFeb 14 at 21:11

Your Answer


By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.