2 回答
TA贡献1803条经验 获得超6个赞
添加所有缺失的中间映射的版本更简单:
private static Map<String, Object> setNested(Map<String, Object> map, List<String> keys, Object value) {
String key = keys.get(0);
List<String> nextKeys = keys.subList(1, keys.size());
Object newValue;
if (nextKeys.size() == 0) {
newValue = value;
} else if (!map.containsKey(key)) {
newValue = setNested(new LinkedHashMap<>(), nextKeys, value);
} else {
newValue = setNested((Map<String, Object>) map.get(key), nextKeys, value);
}
Map<String, Object> copyMap = new LinkedHashMap<>(map);
copyMap.put(key, newValue);
return copyMap;
}
TA贡献1827条经验 获得超8个赞
我看不出YamlParser这个例子有什么用,我也不知道你到底想做什么。我认为,这是关于制作一个新地图,其中复制了中间地图和最终(叶)地图,并且新的叶子地图具有新值。
如果这不是您所需要的,您可以随意修改它。也许它会提示您如何实现自己的方法:
public class Test {
private static Map<String, Object> setNested(Map<String, Object> map, List<String> keys, Object value) {
String key = keys.get(0);
List<String> nextKeys = keys.subList(1, keys.size());
if (nextKeys.size() == 0) {
Map<String, Object> copyMap = new LinkedHashMap<>((Map) map);
copyMap.put(key, value);
return copyMap;
} else if (!map.containsKey(key)) {
return map;
} else {
Map<String, Object> copyMap = new LinkedHashMap<>((Map) map);
Map<String, Object> nextMap = (Map<String, Object>) map.get(key);
copyMap.put(key, setNested(nextMap, nextKeys, value));
return copyMap;
}
}
public static void main(String[] args) {
Map<String, Object> map1 = new LinkedHashMap<>();
Map<String, Object> map2 = new LinkedHashMap<>();
map2.put("lives", 3);
map2.put("deaths", 2);
map1.put("age", 1);
map1.put("human", map2);
System.out.println(map1);
map1 = setNested(map1, Arrays.asList("human", "deaths"), 7);
System.out.println(map1);
}
}
注意:此方法可以在最低级别的映射中插入新键,但不能在中间映射中插入。
添加回答
举报