简体   繁体   English

在 Java 中展平嵌套的 Hashmap

[英]Flatten nested Hashmap in Java

I want to flatten a nested hashmap.我想展平嵌套的哈希图。 For eg,例如,

Map<String, Object> map = new HashMap();
Map<String, Object> map2 = new HashMap();
Map<String, Object> map3 = new HashMap();
map3.put("key3", 123);
map2.put("key2", map3);
map2.put("key4", "test");
map.put("key1", map2);
map.put("key6", "test2");

This will have structure something similar to this:这将具有类似于此的结构:

{
 "key1" : {
            "key2" :  {"key3" : 123 },
            "key4" : "test"  
          },
 "key6" : "test2"
}

This should be flattened to a hashmap with structure similar to this:这应该扁平化为具有类似于以下结构的哈希图:

{
    "key1.key2.key3" : 123,   
    "key1.key4" : "test",
    "key6" : "test2"
}

I tried solving this recursively in Java, but not able to produce the right form.我尝试在 Java 中递归解决这个问题,但无法生成正确的形式。 Any help is appreciated.任何帮助表示赞赏。

Can be acheived using Stream#flatMap and recursion.可以使用Stream#flatMap和递归来实现。

flatMapper() will be recursively called and it will return a Stream of string builder with child keys appended. flatMapper()将被递归调用,它将返回一个附加了子键的字符串构建器流。

public class NestedHashMap {

    private static Stream<StringBuilder> flatMapper(Map.Entry<String, Object> entrySet) {
        Object value = entrySet.getValue();
        if (value instanceof Map) {
            return ((Map<String, Object>) value).entrySet()
                                                .stream()
                                                .flatMap(NestedHashMap::flatMapper)
                                                .map(s -> s.insert(0, entrySet.getKey() + "."));

        }
        return Stream.of(new StringBuilder(entrySet.toString()));
    }

    public static void main(String[] args) {
        // ... Code in the question

        System.out.println(map.entrySet()
                              .stream()
                              .flatMap(NestedHashMap::flatMapper)
                              .collect(Collectors.joining(",\n\t", "{\n\t", "\t\n}")));
    }
}

Output:输出:

{
    key1.key2.key3=123,
    key1.key4=test,
    key6=test2  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM