简体   繁体   English

如何使用java 8流式传输String和Map?

[英]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.

相关问题 如何转换 Map<string ,list> 至 Map <string , map<> &gt; 使用 Java 8</string></string> - How can I convert Map<String ,List > to Map<String , Map<>> using Java 8 如何使用java流过滤地图地图 - How to filter map of map using java stream 如何生成列表的 Map 的 Map(地图<string, map<enum, list<string> &gt;&gt;) 在 java 中使用流</string,> - How do I generate a Map of Map of List (Map<String, Map<Enum, List<String>>>) in java using streams 如何使用Java Stream将map一个Map变成另一个Map? - How to map a Map into another Map using Java Stream? 我如何将 map 的字符串转换为 Java 中的 function? - How can I map a String to a function in Java? Java 8 流:如何转换地图<String, List<Integer> &gt; 到地图<Integer, List<String> &gt; 使用 groupingBy(.) - Java 8 stream: how to Convert Map<String, List<Integer>> to Map<Integer, List<String>> using groupingBy(.) 我可以直接在 Java Stream 中映射属性吗? - Can I map properties directly in Java Stream? 如何使用流API在Java 8中映射? - How do I map this in Java 8 using the stream API? 如何转换流 <Map<Integer, String> &gt;来映射java 8 - How to convert Stream<Map<Integer, String>> to map java 8 转换地图 <Integer, List<Object> &gt;到地图 <Integer, Map<String, Map<LocalDate, Integer> &gt;&gt;使用Java流API - Convert Map<Integer, List<Object>> to Map<Integer, Map<String, Map<LocalDate, Integer>>> using Java stream API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM