java8 多层嵌套MapString Object 遍历查找key为hostname并且value为adrs-ui的位置
你可以使用递归来遍历多层嵌套的Map<String, Object>,并查找key为"hostname",并且value为"adrs-ui"的位置。
下面是一个示例代码:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
Map<String, Object> nestedMap = new HashMap<>();
nestedMap.put("key3", "value3");
nestedMap.put("hostname", "adrs-ui");
map.put("key4", nestedMap);
String key = findKey(map, "hostname", "adrs-ui");
if (key != null) {
System.out.println("Key found: " + key);
} else {
System.out.println("Key not found");
}
}
public static String findKey(Map<String, Object> map, String targetKey, String targetValue) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (key.equals(targetKey) && value.equals(targetValue)) {
return key;
}
if (value instanceof Map) {
String nestedKey = findKey((Map<String, Object>) value, targetKey, targetValue);
if (nestedKey != null) {
return nestedKey;
}
}
}
return null;
}
}
在这个示例中,我们首先创建一个多层嵌套的Map对象,并将其存储在map变量中。然后,我们调用findKey方法来查找key为"hostname",值为"adrs-ui"的位置。如果找到了匹配的位置,就返回对应的key值,否则返回null。
请注意,这个示例假设了每个嵌套的Map中只会有一个匹配的key-value对。如果存在多个匹配的位置,该示例只会返回第一个匹配的key值。如果需要找到所有匹配的位置,可以将返回类型改为List
原文地址: https://www.cveoy.top/t/topic/ilNj 著作权归作者所有。请勿转载和采集!