Nested null check in a map

1k views Asked by At

I am pulling a map value from an external service (which has nested maps). I want to get a value nested a few levels down in that map and perform some actions. The following works but is there a better way to do this? I was attempting with Optional but I don't think it is possible in this case as I can't pass in the method reference something like the following:

Optional.ofNullable(map1)
        .map(Map::get)
        ......

The following is the working example I am trying to amend with Optional or any other suggestions. Please advice.

import org.apache.commons.collections.MapUtils;

    public class A{
        private void methodA(){
            Map<String,Object> map1 = getMap(); // getMap() can return null
            if(MapUtils.isNotEmpty(map1)){
            Map<String, Map<String, String>> map2 = (Map<String, Map<String, String>>) map1.get("key2");
            if(MapUtils.isNotEmpty(map2)){
                Map<String, String> map3 = map2.get("key3");
                if(MapUtils.isNotEmpty(map3)){
                    // do something
                }
            }
        } 
    }

This is the closest answer I found but don't find it to be relevant for a nested map within a map within a map. Java 8 nested null check for a string in a map in a list

2

There are 2 answers

0
Youcef LAIDANI On BEST ANSWER

Are you looking to:

Optional.ofNullable(map1)
        .map(e -> (Map<String, Map<String, String>>) e.get("key2"))
        .map(e -> e.get("key3"))
        .ifPresent(e->{
            // do something
        });
0
Andronicus On

You can use the following chain:

Optional.ofNullable(map1)
    .map(m -> m.get("key2"))
    .map(m -> m.get("key3"))
    .ifPresent(el -> {
        // do something
    });