Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

avoid nested if in hashmap which is created from complex json

Tags:

java

java-8

I have a hashmap which has key value pair of String and object. It is the conversion of something like below json.

{
    "test1": {
        "test2": {
            "test3": {
                "key": "value"
            },
            "somefields12": "some value2"
        },
        "somefields": "some value"
    }
}

But, I am not converting to map. I have just that map. If this may has key and value , I have to do write some logic based on that value. I implemented as below:

    if (map.containsKey("test1") ) {
        final HashMap<String, Object> test1 = (HashMap<String, Object>) map.get("test1");
        if (test1.containsKey("test2")) {
            final List<Object> test2 = (List<Object>) test1.get("test2");
            if (!test2.isEmpty()) {
                final HashMap<String, Object> test3 = (HashMap<String, Object>) test2.get(0);
                if (test3.containsKey("key")) {
                    final String value = String.valueOf(test2.get("key"));
                    if (!StringUtils.isBlank(value)) {
                        //do some work based on value
                    }
                }
            }
        }
    }

Now, I wanted to avoid the nested if (multiple ifs) from my code. What would be the best way to do so?

like image 258
Jacob Avatar asked Aug 02 '18 21:08

Jacob


People also ask

Can you nest HashMaps?

A nested HashMap is Map inside a Map. The only difference between a HashMap and a nested HashMap is: For HashMap , the key or the value can be of any type (object). For Nested HashMap , the key can be of any type (object), but the value is another HashMap object only.

How do I find the value of a nested Map?

You can get the nested value by repeating . get() , but with deeply nested maps you have to do a lot of casting into Map . An easier way is to use a generic method for getting a nested value.

Can Hashmaps have multiple values?

HashMap can be used to store key-value pairs. But sometimes you may want to store multiple values for the same key. For example: For Key A, you want to store - Apple, Aeroplane.

Can we have Map inside Map in Java?

In Java, Map is an interface that maps keys to values. Sometimes it is required to implement Map of Map (nested Map). Nested Map is used in many cases, such as storing students' names with their Ids of different courses.


1 Answers

I'm not familiar with the fancy new Java 8 features, so I'd do it the old fashioned way with a function that takes a path to look up, and walks the list with a loop:

import java.util.*;

class Test {

  static String getByPath(HashMap<String, Object> map, String... path) {
    for(int i=0; i<path.length-1; i++) {
      map = (HashMap<String, Object>) map.get(path[i]);
      if (map == null) return null;
    }
    Object value = map.get(path[path.length-1]);
    return value == null ? null : String.valueOf(value);
  }

  public static void main(String[] args) {
    HashMap<String, Object> map = new HashMap<>();
    HashMap<String, Object> tmp1 = new HashMap<>();
    HashMap<String, Object> tmp2 = new HashMap<>();
    map.put("test1", tmp1);
    tmp1.put("test2", tmp2);
    tmp2.put("key1", "My Value");

    System.out.println("With valid path:   " + getByPath(map, "test1", "test2", "key1"));
    System.out.println("With invalid path: " + getByPath(map, "test1", "BANANA", "key1"));
  }
}

This results in:

With valid path:   My Value
With invalid path: null

This can optionally be extended to:

  • Check that nodes are in fact maps before casting
  • Use Optional or a helpful exception instead of returning null
like image 143
that other guy Avatar answered Sep 30 '22 20:09

that other guy