I'm new to java.
I need to get the HashMap value from Nested HashMap
using its key path and the key is a dynamic variable.
For example the HashMap is
{data={
"owner" : {
"id" : 34,
"firstName" : "John",
"lastName" : "Smith",
"owner" : {
"id" : 44,
"firstName" : "Henrick",
"lastName" : "kane"
},
},
"fname" : "sahal",
"lname" : "kn",
}
}
And I get the keys like data.owner.owner.id
or data.owner.id
or fname
. So the length of the key path can be any number. above example it is 4
, 3
and 1
. It can be 5, 6, or 7 any. Keys are dynamic so i can't predict how many length to reach the last key value.
Is there a way I can dynamically pull the HashMap value, list like below myHashMaoVariable.get("data.owner.owner.id");
Now what i'm splitting the key data.owner.id
to a list and checking
if key[0] > 1 and myHashMaoVariable.containsKey(key[0]), if key[1] > 1 and myHashMaoVariable.get(key[0]).containsKey(key[1]), if key[2] > 1 and myHashMaoVariable.get(key[0]).get(key[1]).containsKey(key[1]),
ans so on till key length 5.
Is there a better way to do it to support n number of key path length ? Also there is no depth
to the nested map. It is also dynamic.
Supposing you have a top-level map:
Map<String, Object> rootMap = ...//obtain map
You can define a method that reads values up to a certain level dynamically:
static Object readKeyValue(String keyPath, Map<String, Object> root) {
String[] keys = keyPath.split("\\.");
Object value = root.get(keys[0]);
for (int i = 1; i < keys.length; i++) {
if (i == keys.length - 1) {
return ((Map<String, Object>) value).get(keys[i]);
} else {
value = ((Map<String, Object>) value).get(keys[i]);
}
}
return value;
}
With such a method, you can just invoke it with:
Object value = readKeyValue("data.owner.owner.id", rootMap);
Tested with the following main method:
public static void main(String[] args) {
Map<String, Object> rootMap = new HashMap<>(), data = new HashMap<>(), owner1 = new HashMap<>(),
owner2 = new HashMap<>();
rootMap.put("data", data);
data.put("owner", owner1);
owner1.put("owner", owner2);
owner2.put("firstName", "something");
System.out.println(rootMap);
System.out.println(readKeyValue("data.owner.owner.firstName", rootMap));
}
And the following output was produced:
{data={owner={owner={firstName=something}}}}
something
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.