Java 8 stream map to list of keys sorted by values

前端 未结 6 1278
夕颜
夕颜 2020-12-03 06:29

I have map Map countByType and I want to have a list which has sorted (min to max) keys by their corresponding values. My try is:



        
6条回答
  •  时光取名叫无心
    2020-12-03 07:13

    You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting

    countByType.entrySet()
               .stream()
               .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
               .map(e -> e.getKey())
               .collect(Collectors.toList());
    

提交回复
热议问题