Search code examples
javajava-stream

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<Int, List<Map<String, Boolean>>>, I want to populate a set that has Int as key of the outer map based on condition.

MyService.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. How can I do this using java 8 streams?

I tried with for loop, but I will like to replace it using Java streams.


Solution

  • This produced the same results as your code in a test that passed "test_1", etc. into it.

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