你可以使用递归来遍历多层嵌套的 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,并在匹配到 key 时添加到列表中。

Java 8 递归遍历多层嵌套 Map 查找特定键值对

原文地址: https://www.cveoy.top/t/topic/p3PT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录