我有以下结构:

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/

10-12 05:51