【问题标题】:Java 8 - Sort Map by value and collect results [duplicate]Java 8 - 按值排序地图并收集结果
【发布时间】:2015-10-05 22:34:12
【问题描述】:

我正在尝试使用 JDK 8 样式函数按其值对 Map 进行排序。虽然我得到了排序部分,但我不确定如何在 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())
            ;

【问题讨论】:

标签: java-8


【解决方案1】:

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

    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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-09
    • 2019-03-16
    • 1970-01-01
    • 2018-02-07
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多