I have a nested HashMap
with String
keys that contains either List
, Map
, or String
values. I would like to f
You can use recursion to flatten the Map
. Each time you encounter a Map
, recurse by flattening that Map
; when you encounter a List
, iterate over it and add the index to the current key. A single value can be trivially set otherwise. See the below code in action here.
public static Map flatten(final Map map) {
return flatten("", map, new HashMap<>());
//use new TreeMap<>() to order map based on key
}
@SuppressWarnings("unchecked")//recursive helper method
private static Map flatten(final String key, final Map map,
final Map result) {
final Set> entries = map.entrySet();
if (!entries.isEmpty()) {
for (final Map.Entry entry : entries) {
//iterate over entries
final String currKey = key + (key.isEmpty() ? "" : '.') + entry.getKey();
//append current key to previous key, adding a dot if the previous key was not an empty String
final Object value = entry.getValue();
if (value instanceof Map) {//current value is a Map
flatten(currKey, (Map) value, result);//flatten Map
} else if (value instanceof List) {//current value is a List
final List