简体   繁体   English

Java 中 Map 列表的 Map 迭代流

[英]Streams for iterating through Map of List of Map in Java

I have a map that contains Integer as key and (List of Map of String as key and boolean as the value) as value.我有一个 map,其中包含 Integer 作为键和(Map 的字符串列表作为键,boolean 作为值)作为值。 Map<Int, List<Map<String, Boolean>>>, I want to populate a set that has Int as key of the outer map based on condition. Map<Int, List<Map<String, Boolean>>>,我想根据条件填充一个以 Int 作为外部 map 键的集合。

MyService.java我的服务.java


public Set<Integer> getValue(String input){
        Map<String, Boolean> in1 = new HashMap<>();
        in1.put("test_1", true);
        Map<String, Boolean> in2 = new HashMap<>();
        in2.put("test_2", false);
        Map<String, Boolean> in3 = new HashMap<>();
        in2.put("test_3", false);
        Map<String, Boolean> in4 = new HashMap<>();
        in2.put("test_4", true);
        List<Map<String, Boolean>> l1 = new ArrayList<>();
        l1.add(in1);
        l1.add(in2);
        List<Map<String, Boolean>> l2 = new ArrayList<>();
        l2.add(in3);
        l2.add(in4);
        Map<Integer, List<Map<String,Boolean>>> map = new HashMap();
        map.put(123, l1);
        map.put(345, l2);

        Set<Integer> result = new HashSet<>();
        for(Map.Entry<Integer, List<Map<String, Boolean>>> entry : map.entrySet()){
            for(Map<String, Boolean> m: entry.getValue() ){
                if(m.containsKey(input) && m.get(input) == true){
                    result.add(entry.getKey());
                }
            }
        }
        return result;
    }

So, basically I want to iterate from first the exterior map to get the internal map and then iterate the internal map to check if the input is present and add it to a set.所以,基本上我想从外部 map 开始迭代以获得内部 map 然后迭代内部 map 以检查输入是否存在并将其添加到集合中。 How can I do this using java 8 streams?我如何使用 java 8 流来做到这一点?

I tried with for loop, but I will like to replace it using Java streams.我尝试使用 for 循环,但我想用 Java 流替换它。

This produced the same results as your code in a test that passed "test_1", etc. into it.这产生了与您的代码在将“test_1”等传递给它的测试中相同的结果。

map.entrySet().stream()
    .filter(entry -> entry.getValue().stream()
        .anyMatch(m -> m.getOrDefault(input, false)))
    .map(Map.Entry::getKey)
    .collect(Collectors.toSet());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM