How to know if a key exists in inner map using java?
In the below map how do I know if key3 exists without going through a brute force for-loop and check inside every inner map. Given that all keys will be unique do we have any library functions doing it?
"map": {
"key1": "value1",
"innerMap": {
"key2": "value2",
"innerMap2": {
"key3": "value3"
}
}
}
Assuming that your picture describes a Map
, then a "brute-force" tree traversal is your best option.
There is no standard Java SE API for searching nested maps.
@f1sh mentioned the possibility of doing a string search ... assuming that the map is actually JSON. There are some important caveats:
-
String searching a JSON string (or the result of calling
Map.toString()
) is potentially fragile. For example,.contains("\"key3\":")
would give false matches if a value in the map contained that search string. -
Rendering a
Map
to JSON (or whatever) to do a string search will be more expensive than doing the search. -
A
String.contains
search potentially entails looking at every character in the serialization. That's just as "brute-force" as a tree traversal.
The only alternative that I can think of that is not "brute-force" is to create an auxiliary data structure; e.g. HashSet
of all (unique) keys in the map tree. Once created, the set can be queried in O(1)
... but creating it is O(N)
where N
is the number of (non-distinct!) keys in the tree.
Finally, the map tree traversal could be a recursive method rather than (just) a mess of for
loops.