[英]How can I stream a Map of String and Map using java 8?
I have a Map<Key1, Map<Key2, CustomObject>>
. 我有一个
Map<Key1, Map<Key2, CustomObject>>
。 I need go through the Map
, check if Key2.equals("a string")
and return a Map<Key1, CustomObject>
. 我需要浏览
Map
,检查Key2.equals("a string")
并返回Map<Key1, CustomObject>
。
Is this possible with java 8? 这有可能与Java 8? Should it be done with java 8 or is it better with nested for loops?
它应该用java 8完成还是嵌套for循环更好?
You can filter the entries of the input Map
to keep only entries whose value contains the "a string" key. 您可以过滤输入
Map
的条目,以仅保留其值包含“a string”键的条目。 Then use Collectors.toMap
to collect them into a new Map
: 然后使用
Collectors.toMap
将它们收集到一个新的Map
:
Map<Key1, CustomObject> map =
inputMap.entrySet()
.stream()
.filter(e -> e.getValue().containsKey("a string"))
.collect(Collectors.toMap(Map.Entry::getKey,
e -> e.getValue().get("a string")));
it also works 它也有效
Map<String, SocialCredentials> collect = configData.getData()
.entrySet().stream()
.map(map -> map.getValue()
.entrySet().stream()
.filter(entry ->
profile.toLowerCase().equals(entry.getKey()))
.collect(Collectors.toMap(p -> map.getKey(),
Map.Entry::getValue)))
.collect(HashMap::new, Map::putAll, Map::putAll);
but your solution is more suitable in my case. 但是你的解决方案更适合我的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.