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

Bob*_*dru 4 java java-8 java-stream

我有一个Map<Key1, Map<Key2, CustomObject>>.我需要通过Map,检查是否Key2.equals("a string")返回Map<Key1, CustomObject>.

这有可能与Java 8?它应该用java 8完成还是嵌套for循环更好?

Era*_*ran 10

您可以过滤输入的条目,Map以仅保留其值包含"a string"键的条目.然后使用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")));
Run Code Online (Sandbox Code Playgroud)