从Java中的路径字符串生成嵌套映射

时间:2018-07-16 01:12:07

标签: java

我想基于输入路径Map和一个String生成一个嵌套的Object,以在最终内部值处使用。

以下是使用示例路径并严格生成嵌套Map结构的示例方法:

   public Map<String, Object> generateNestedMap(String path, Object value)
   {
      // dot delimited path for the nested map
      path = "foo.bar.baz"; // For example

      // Hard coded nested map generation based on example hard coded path string.
      // Ideally, this should also be much more elegant. 
      Map<String, Object> fooMap = new HashMap<>();
      Map<String, Object> barMap = new HashMap<>();
      Map<String, Object> bazMap = new HashMap<>();
      bazMap.put("baz", value);
      barMap.put("bar", bazMap);
      fooMap.put("foo", barMap);

      return fooMap;
   }

最终,我的目标是基于提供的 path value 参数生成任意嵌套的Map

2 个答案:

答案 0 :(得分:1)

以下实现将做到这一点:

public static Map<String, Object> generateNestedMap(String path, Object value) {
    int end = path.length();
    for (int start; (start = path.lastIndexOf('.', end - 1)) != -1; end = start)
        value = new HashMap<>(Collections.singletonMap(path.substring(start + 1, end), value));
    return new HashMap<>(Collections.singletonMap(path.substring(0, end), value));
}

测试

System.out.println(generateNestedMap("foo.bar.baz", 5));

输出

{foo={bar={baz=5}}}

如果您想添加到现有地图,以便将多个调用合并在一起,请执行以下操作:

@SuppressWarnings("unchecked")
public static void generateNestedMap(Map<String, Object> map, String path, Object value) {
    int start = 0;
    for (int end; (end = path.indexOf('.', start)) != -1; start = end + 1)
        map = (Map<String, Object>) map.computeIfAbsent(path.substring(start, end), k -> new HashMap<String, Object>());
    map.put(path.substring(start), value);
}

测试

Map<String, Object> map = new HashMap<>();
generateNestedMap(map, "foo.bar.baz", 5);
generateNestedMap(map, "foo.qux.corge", 6);
System.out.println(map);

输出

{foo={bar={baz=5}, qux={corge=6}}}

答案 1 :(得分:1)

使用递归:-

cwDebugParen

测试:typedef struct flag { int8_t (*valid)(Flag flag); const uint8_t requiresValue; const char* name; uint8_t active; char* value; } Flag;

输出:public static Map<String, Object> generateNestedMap(String path, Object value) { final int indexOfDot = path.indexOf('.'); return indexOfDot == -1 ? Collections.singletonMap(path, value) : Collections.singletonMap(path.split("\\.")[0], generateNestedMap(path.substring(indexOfDot + 1), value)); }