您可以使用递归来展平
Map。每次遇到a时
Map,通过展平来递归
Map;
当您遇到时
List,请对其进行迭代,然后将索引添加到当前键中。否则,可以简单地设置一个值。在行动中看到下面的代码在这里。
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 methodprivate 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);}


