我有以下类型的嵌套 map LinkedHashMap<String, LinkedHashMap<String, ArrayList<Commit>>>
.第一个映射的键存储一些用户名,第二个映射的键是用户的存储库名称,在 ArrayList 中我有一个对象具有一些属性,如散列、消息、添加等。
在我按第一个 map 的键和第二个 map 的键按字母顺序对整个集合进行排序后,如何将我的嵌套 map 收集(保存)到相同类型的新集合中(对象保持不变)?
我需要使用 lambda 和 Stream API 来执行此操作。这是我尝试这样做的方式:
LinkedHashMap<String, LinkedHashMap<String, ArrayList<Commit>>> sorted = gitUsers.entrySet()
.stream()
.sorted((u1, u2) -> u1.getKey().compareTo(u2.getKey()))
.map(u -> u.getValue()
.entrySet()
.stream()
.sorted((r1, r2) -> collator.compare(r1.getKey(), r2.getKey())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(a, b) -> a, LinkedHashMap::new));
我肯定做错了什么,因为我不断收到以下消息“无法从静态上下文中引用非静态方法”并且无法收集 map 。我想我无法成功组装我的 map 是因为 .map()
函数和我使用的第二个流。
我知道您会建议我使用 TreeMap 或对集合进行排序并使用 .foreach()
立即打印它我的 lambda 中的方法(我已经顺便做了),但我需要完全按照我上面描述的方式来做。
为了我的编程基础类(class)的目的,这个问题应该以这种方式解决。希望得到您的帮助!
附言我在很长一段时间内一直在寻找解决方案,并在包括 Stack Overflow 论坛在内的所有地方进行了研究,但没有找到与要求的解决问题的方法相对应的任何内容。
最佳答案
即使我删除了未知的 collator
比较器的排序,你的代码也没有编译。
有效代码是:
Map<String, Map<String, List<Commit>>> collect = h.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue()
.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(a, b) -> a,
LinkedHashMap::new
)
),
(a, b) -> a,
LinkedHashMap::new
)
);
请注意,您可以用比较器代替 Map.Entry.comparingByKey()
。
关于Java 8 : How to sort and collect two nested Maps with ArrayList inside?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46003804/