Flatten nested Map containing with unknown level of nested Arrays and Maps recursively

后端 未结 2 1193
野的像风
野的像风 2021-01-19 15:06

I have a nested HashMap with String keys that contains either List, Map, or String values. I would like to f

2条回答
  •  攒了一身酷
    2021-01-19 15:29

    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 list = (List) value;
                    for (int i = 0, size = list.size(); i < size; i++) {
                        result.put(currKey + '.' + (i + 1), list.get(i));
                    }
                    //iterate over the List and append the index to the current key when setting value
                } else {
                    result.put(currKey, value);//set normal value
                }
            }
        }
        return result;
    }
    public static void main(final String[] args){
        final Map flattened = flatten(dates);
        System.out.println(flattened);
    }
    
        

    提交回复
    热议问题