我有以下对象和地图:
MyObject
String name;
Long priority;
foo bar;
Map<String, List<MyObject>> anotherHashMap;
我想在另一张地图中转换地图。结果映射的键是输入映射的键。结果映射的值列出了我的对象的属性“名称”,按优先级排序。
排序和提取名称不是问题,但我无法将其放入结果映射中。我是用旧的Java 7方式来做的,但是如果可以使用流API,那就太好了。
Map<String, List<String>> result = new HashMap<>();
for (String identifier : anotherHashMap.keySet()) {
List<String> generatedList = anotherHashMap.get(identifier).stream()...;
teaserPerPage.put(identifier, generatedList);
}
有什么主意吗?我试过了,但被卡住了:
anotherHashMap.entrySet().stream().collect(Collectors.asMap(..., ...));
发布于 2014-12-12 19:18:55
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
作为映射,并将生成的名称收集到列表中。
发布于 2014-12-12 16:53:24
为了生成另一张地图,我们可以有如下内容:
HashMap<String, List<String>> result = anotherHashMap.entrySet().stream().collect(Collectors.toMap(elem -> elem.getKey(), elem -> elem.getValue() // can further process it);
上面我正在重新创建地图,但您可以根据您的需要处理键或值。
发布于 2014-12-13 02:27:58
Map<String, List<String>> result = anotherHashMap.entrySet().stream().collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().stream()
.sorted(comparing(MyObject::getPriority))
.map(MyObject::getName)
.collect(Collectors.toList())));
类似于Mike的答案,但排序被应用于正确的位置(即值被排序,而不是映射项),并且使用更简洁的静态方法Comparator.comparing
来获得排序的比较器。
https://stackoverflow.com/questions/27448266
复制相似问题