Java 8 - 按值排序地图并收集结果

时间:2015-10-05 22:34:13

标签: java-8

我正在尝试使用JDK 8样式函数对其值进行排序。虽然我得到了排序部分,但我不确定如何在TreeMap中收集结果。有人可以解释如何以声明风格完成这项工作吗?

我需要收集到另一个Map<String, String>

    Map<String, String> map = new HashMap<>();
    map.put("John", "time3");
    map.put("Henry", "time6");
    map.put("Smith", "time1");
    map.put("Rock", "time2");
    map.put("Ryan", "time5");
    map.put("Gosling", "time4");

   map.entrySet().stream()
            .sorted(Map.Entry.<String, String>comparingByValue().reversed())
            ;

1 个答案:

答案 0 :(得分:1)

虽然有几个类似的问题,但我明确希望将结果存储在Map中。这是解决方案。

    Map<String, String> sortedMap = map.entrySet().stream()
            .sorted(Map.Entry.<String, String>comparingByValue().reversed())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v2, LinkedHashMap::new));
相关问题