Home > Net >  Checking if value present in a nested Map using lambda expression
Checking if value present in a nested Map using lambda expression

Time:01-20

I have a nested map as Map<String, Map<String, Boolean>> and would like to find if the inner map has at least one value as TRUE. I was able to do it using a loop but trying to do it using lambda expression

Using for loop:

        Map<String, Map<String, Boolean>> maps = new HashMap<>();
        Map<String, Boolean> test = new HashMap<>();
        test.put("test1", Boolean.FALSE);
        test.put("test2", Boolean.TRUE);
        maps.put("hey", test);
        Map<String, Boolean> testtt = new HashMap<>();
        testtt.put("test3", Boolean.FALSE);
        testtt.put("test4", Boolean.TRUE);
        maps.put("lol", testtt);
        Boolean val = Boolean.FALSE;
        for(Map.Entry<String, Map<String, Boolean>> m: maps.entrySet()){
            Map<String, Boolean> mm = m.getValue();
            for(Map.Entry<String, Boolean> mmm: mm.entrySet()){
                if(mmm.getValue()){
                    val = Boolean.TRUE;
                    break;

                }
            }
        }

        System.out.println(val);

CodePudding user response:

You can try changing the loop on something like this:

Map<String, Map<String, Boolean>> maps = new HashMap<>();
boolean hasValue = maps
.values()
.stream()
.flatMap(m -> m.values().stream())
.anyMatch(b -> b.getValue());

CodePudding user response:

I was able to do it using a loop but trying to do it using lambda expression.

Here is one way. Here the lambda will be based on a Predicate

  • first you need to stream the outer maps values (which is another map) and then stream the values of those.
  • Then it's a matter of using anyMatch() with an identity lambda to find the first true value.
Predicate<Map<String, Map<String, Boolean>>> hasTrue = m -> m.values()
        .stream().flatMap(map -> map.values().stream()).anyMatch(a->a);

System.out.println(hasTrue.test(maps));

Prints

true

  • Related