HashMap of HashMaps traversal
In Java, I'm trying to retrieve a HashMap<String, Object>
that has the Object which is: HashMap<String, Object&g开发者_StackOverflowt;
.
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:
return getHashMap((HashMap<String, Object>) entry.getValue(), key);
you want to first check if it is not null
, and return it only then. Otherwise you should just continue searching:
HashMap<String, Object> result = getHashMap((HashMap<String, Object>) entry.getValue(), key);
if (result != null)
return result;
For one, don't use ==
for Strings. Instead use the equals method.
For another, I prefer to do instanceof such as if (myObject instanceof java.util.Map) { ... }
this way your map doesn't have to be a HashMap if later you decide to change it.
Another approach. Try use HashMap<String, HashMap<String, Object>> main
for your 'outer' HashMap, then you'll search for key
:
Object value = main.get(key);
if (value == null) {
for (HashMap<String, Object> inner : main.values()) {
value = inner.get(key);
if (value != null) {
break;
}
}
}
精彩评论