gpt4 book ai didi

java - 将值放入 LinkedHashMap 多维

转载 作者:行者123 更新时间:2023-12-02 06:16:38 25 4
gpt4 key购买 nike

我有以下结构:

import java.util.LinkedHashMap;
...
LinkedHashMap <String, Object>level0 = new LinkedHashMap<String, Object>();
LinkedHashMap <String, Object>level1 = new LinkedHashMap<String, Object>();
LinkedHashMap <String, Object>level2 = new LinkedHashMap<String, Object>();
LinkedHashMap <String, Object>level3 = new LinkedHashMap<String, Object>();

level1.put("level2", level2);
level2.put("level2", level3);

level0.put("level1", level1);

System.out.println(level0);

输出:

{
level1={
level2={}
}
}

我需要通过“路径”(或其他东西)设置一个值,如下所示:

MapThisObject example = new MapThisObject(level0);
example.putValue("level1.level2", "string", "test");
example.putValue("level1.level2", "int", 1);
example.putValue("level1.level2", "object", new LinkedHashMap());

System.out.println(example.result());
/*output:
{
level1={
level2={
string="test",
int=1,
Object={}
}
}
}
*/

换句话说,有可能通过“路径”(如 Xpath)为“多维对象”放置或设置值?

最佳答案

一个简单的例子

public static void set(Map<String, Object> map, String path, Object value) {
String[] parts = path.split("\\.");
for(int i = 0; i < parts.length-1 ; i++) {
String key = parts[i];
Map<String, Object> map2 = (Map<String, Object>) map.get(key);
if (map2 == null) {
map.put(key, map2 = new LinkedHashMap<String, Object>());
}
map = map2;
}
map.put(parts[parts.length - 1], value);
}

set(example, "level1.level2.string", "test");
set(example, "level1.level2.int", 1);

关于java - 将值放入 LinkedHashMap 多维,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21389474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com