Java 8 stream map to list of keys sorted by values

前端 未结 6 1283
夕颜
夕颜 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:09

    You say you want to sort by value, but you don't have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort.

    And you want to get the keys; use map to transform entries to keys.

    List types = countByType.entrySet().stream()
            .sorted(Comparator.comparing(Map.Entry::getValue))
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
    

提交回复
热议问题