Reputation: 425
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.
Upvotes: 3
Views: 1182
Reputation: 2488
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
}
Upvotes: 2