【问题标题】:Sorting HashMap String values using Java 8 Stream doesn't work [duplicate]使用 Java 8 Stream 对 HashMap 字符串值进行排序不起作用 [重复]
【发布时间】:2016-10-02 04:19:10
【问题描述】:

我正在使用来自this 问题的解决方案对LinkedHashMap 中的字符串值进行排序。然而,排序根本不起作用。这是我写的代码。

Map<Integer, String> sortedMap = myMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry<Integer, String>::getKey, 
                    Map.Entry<Integer, String>::getValue));

myMap = new LinkedHashMap<Integer, String>(sortedMap);

奇怪的是,当同时使用comparingByValuecomparingByKey 方法时,它正在对Integerkeys 进行排序。所以它肯定是排序,只是不是String 值,而是Integer 键。我不明白我在这里做错了什么。

【问题讨论】:

  • 我的猜测是Collectors.toMap 正在将它们收集到哈希映射中,从而破坏了排序。
  • 这是有道理的。但是,这仍然不能解释整数键的排序。
  • 整数似乎已排序,因为整数值本身用作哈希,但是一旦添加更多整数,您可能会得到不同的顺序,因为重新哈希/多个项目最终在同一个存储桶中。

标签: java sorting hashmap java-8 java-stream


【解决方案1】:

您正在使用的toMap 收集器将元素放在HashMap 中,因此在这里排序没有帮助,因为您最终会将它们放在无序的集合中。

使用重载的toMap 方法,并提供LinkedHashMap 作为具体实例,即:

Map<Integer, String> sortedMap = 
     myMap.entrySet()
          .stream()
          .sorted(Map.Entry.comparingByValue())
          .collect(Collectors.toMap(Map.Entry::getKey,
                                    Map.Entry::getValue, 
                                    (a, b) -> a, //or throw an exception
                                    LinkedHashMap::new));

【讨论】:

  • 从技术上讲,没有指定 toMap 将返回哪种地图。当前的 Oracle 实现确实使用了HashMap
  • 是的,对不起。我应该说“该实现不对地图的属性做任何保证,并且目前在幕后使用 HashMap。如果您需要特定的实现,请使用重载的toMap 方法。”
  • @AlexisC。抱歉,你觉得stackoverflow.com/q/61844376/811293
【解决方案2】:

我的猜测是 Collectors.toMap 正在将它们收集到一个无序的地图中,立即破坏了排序。

尝试直接在LinkedHashMap 中收集它们:

LinkedHashMap<Integer, String> newMap = new LinkedHashMap<>();
Map<Integer, String> sortedMap = myMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .collect((k, v) -> newMap.put(k, v));
myMap = newMap;

至于为什么要对整数键进行排序:这可能只是巧合,基于HashMap 对键进行分桶的方式。

【讨论】:

    猜你喜欢
    • 2017-02-18
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多