How to use thenComparing in java stream

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-30 02:53:12

问题


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.


回答1:


How about

String out = outMap.values().stream()
        .sorted(Comparator.comparingInt(String::length)
                          .thenComparing(Comparator.naturalOrder()))
                    //OR  .thenComparing(String.CASE_INSENSITIVE_ORDER))
        .collect(Collectors.joining());


来源:https://stackoverflow.com/questions/48796108/how-to-use-thencomparing-in-java-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!