简体   繁体   中英

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. Any help is appreciated.

Can be acheived using Stream#flatMap and recursion.

flatMapper() will be recursively called and it will return a Stream of string builder with child keys appended.

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  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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