Java 8 stream map to list of keys sorted by values

前端 未结 6 1284
夕颜
夕颜 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

    Map map = new HashMap<>();
    map.put(1, "B");
    map.put(2, "C");
    map.put(3, "D");
    map.put(4, "A");
    
    List list = map.values()
                           .stream()
                           .sorted()
                           .collect(Collectors.toList());
    

    Output: [A, B, C, D]

提交回复
热议问题