0

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

Naman
  • 27,789
  • 26
  • 218
  • 353
karvai
  • 2,417
  • 16
  • 31
  • Root cause for all of this - *"getMap() can return null"*. Fix that! I can second the fact that sometimes its unavoidable to use `Map`, but casting one of its value further to `Map>` is way too poor a choice. – Naman Mar 11 '20 at 15:50
  • @Naman What would have been a better alternative? Cos it comes to me in a from external call where its object cos the mapping is in various values of Lists and Maps and Strings. Whereas I know that the value I am extracting from that initial map is Map> – karvai Mar 12 '20 at 12:03

2 Answers2

4

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
        });
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
2

You can use the following chain:

Optional.ofNullable(map1)
    .map(m -> m.get("key2"))
    .map(m -> m.get("key3"))
    .ifPresent(el -> {
        // do something
    });
Andronicus
  • 25,419
  • 17
  • 47
  • 88