Java 8 streams: iterate over Map of Lists(Java 8 流:迭代列表映射)
问题描述
我有以下对象和地图:
MyObject
String name;
Long priority;
foo bar;
Map<String, List<MyObject>> anotherHashMap;
我想将地图转换为另一个地图.结果映射的键是输入映射的键.结果映射的值是我的对象的属性名称",按优先级排序.
I want to convert the Map in another Map. The Key of the result map is the key of the input map. The value of the result map ist the Property "name" of My object, ordered by priority.
ordering 和提取名称不是问题,但我无法将其放入结果图中.我用旧的 Java 7 方式来做,但如果可以使用流式 API,那就太好了.
The ordering and extracting the name is not the problem, but I could not put it into the result map. I do it the old Java 7 way, but it would be nice it is possible to use the streaming API.
Map<String, List<String>> result = new HashMap<>();
for (String identifier : anotherHashMap.keySet()) {
List<String> generatedList = anotherHashMap.get(identifier).stream()...;
teaserPerPage.put(identifier, generatedList);
}
有人知道吗?我试过了,但卡住了:
Has anyone an idea? I tried this, but got stuck:
anotherHashMap.entrySet().stream().collect(Collectors.asMap(..., ...));
推荐答案
Map<String, List<String>> result = anotherHashMap
.entrySet().stream() // Stream over entry set
.collect(Collectors.toMap( // Collect final result map
Map.Entry::getKey, // Key mapping is the same
e -> e.getValue().stream() // Stream over list
.sorted(Comparator.comparingLong(MyObject::getPriority)) // Sort by priority
.map(MyObject::getName) // Apply mapping to MyObject
.collect(Collectors.toList())) // Collect mapping into list
);
本质上,您流过每个条目集并将其收集到新地图中.要计算新地图中的值,您需要对旧地图中的 List<MyOjbect>
进行流式传输、排序,然后对其应用映射和收集函数.在这种情况下,我使用 MyObject::getName
作为映射并将生成的名称收集到一个列表中.
Essentially, you stream over each entry set and collect it into a new map. To compute the value in the new map, you stream over the List<MyOjbect>
from the old map, sort, and apply a mapping and collection function to it. In this case I used MyObject::getName
as the mapping and collected the resulting names into a list.
这篇关于Java 8 流:迭代列表映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 流:迭代列表映射


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01