展平嵌套的Map,其中包含未知级别的嵌套数组,并且递归地映射 [英] Flatten nested Map containing with unknown level of nested Arrays and Maps recursively

查看:122
本文介绍了展平嵌套的Map,其中包含未知级别的嵌套数组,并且递归地映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的HashMap,其中包含String键,其中包含ListMapString值.我想像下面这样压扁它们.

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

以下是数据:

import java.util.*;
import java.util.stream.*;
public class MyClass {
    public static void main(String args[]) {
        Map<String, Object> dates = new HashMap<String, Object>() {{
            put("1999", new HashMap<String, Object>() {{
                put("3", Arrays.asList("23", "24", "25"));
                put("4", Arrays.asList("1", "2", "3"));
            }});
            put("2001", new HashMap<String, Object>() {{
                put("11", new HashMap<String, Object>() {{
                    put("7", Arrays.asList("23", "24", "25"));
                    put("9", Arrays.asList("1", "2", "3"));
                }});
                put("12", "45");
            }});
        }};
        System.out.println(dates);
    }
}

地图如下:

{2001={11={7=[23, 24, 25], 9=[1, 2, 3]}, 12=45},
 1999={3=[23, 24, 25], 4=[1, 2, 3]}}

地图的拼合应如下所示:

The flattening of map should look like this:

{2001.11.7.1=23, 2001.11.7.2=24, 2001.11.7.3=25, 2001.11.9.1=1, 2001.11.9.2=2, 
 2001.11.9.3=3, 2001.12=45, 1999.3.1=23, 1999.3.2=24, 1999.3.3=25,
 1999.4.1=1, 1999.4.2=2, 1999.4.3=3}

注意:嵌套数组或地图的级别未知,可能会超过2个级别.

Note: the level of nested arrays or maps is unknown, it may go more than 2 levels.

推荐答案

您可以使用递归来展平Map.每次遇到Map时,通过展平该Map进行递归.当您遇到List时,请对其进行迭代并将索引添加到当前键中.否则,可以简单地设置一个值.请在此处中查看下面的代码.

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<String, Object> flatten(final Map<String, Object> map) {
    return flatten("", map, new HashMap<>());
    //use new TreeMap<>() to order map based on key
}

@SuppressWarnings("unchecked")//recursive helper method
private static Map<String, Object> flatten(final String key, final Map<String, Object> map,
        final Map<String, Object> result) {
    final Set<Map.Entry<String, Object>> entries = map.entrySet();
    if (!entries.isEmpty()) {
        for (final Map.Entry<String, Object> 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<String, Object>) value, result);//flatten Map
            } else if (value instanceof List) {//current value is a List
                final List<Object> list = (List<Object>) 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<String, Object> flattened = flatten(dates);
    System.out.println(flattened);
}

这篇关于展平嵌套的Map,其中包含未知级别的嵌套数组,并且递归地映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆