In Java, I’m trying to retrieve a HashMap<String, Object> that has the Object which is: HashMap<String, Object>.
I implemented a recursive function that returns either the HashMap<String, Object> found with the given key, or null if the key wasn’t found.
Here is the function:
public static HashMap<String, Object> getHashMap(HashMap<String,
Object> map, String key)
{
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getValue().getClass().getName() == "java.util.HashMap") {
if (entry.getKey() == key)
return (HashMap<String, Object>) entry.getValue();
return getHashMap((HashMap<String, Object>) entry.getValue(), key);
}
}
return null;
}
It only works for the first item. How do I traverse a Hashmap of HashMaps? What is a better approach?
Instead of returning the value immediately here:
you want to first check if it is not
null, and return it only then. Otherwise you should just continue searching: