【问题标题】:How can I sort a HashMap<String, Pair<Double, Integer>> by Double Value?如何按双值对 HashMap<String, Pair<Double, Integer>> 进行排序?
【发布时间】:2018-12-05 13:42:25
【问题描述】:

如何使用 Stream 按 Double 参数中的值对 HashMap&lt;String, Pair&lt;Double, Integer&gt;&gt; myMap 进行排序?

【问题讨论】:

  • 你有什么尝试吗?请向我们展示您的代码。
  • 简短的回答,您不能对 HashMap 进行排序,因为它不保留任何顺序痕迹。
  • 投票结束,因为没有尝试解决问题。

标签: java sorting dictionary java-stream


【解决方案1】:

sorted 方法与以下比较器一起使用并收集到LinkedHashMap

Map<String, Pair<Double, Integer>> result = map.entrySet()
                .stream()
                .sorted(Comparator.comparingDouble(e -> e.getValue().getKey()))
                .collect(toMap(Map.Entry::getKey,
                        Map.Entry::getValue,
                        (l, r) -> l,
                        LinkedHashMap::new));

【讨论】:

  • 请注意,toMapCollectors.toMap,如果您没有静态导入 toMap 方法。
  • @nullpointer 如果您想关闭问题、删除或其他任何操作,请使用您的权限执行此操作。我无话可说。
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
相关资源
最近更新 更多