!1368 将多层级Map处理为一个层级Map类型

Merge pull request !1368 from ckpaly/v5-dev
This commit is contained in:
Looly
2025-07-30 11:05:25 +00:00
committed by Gitee
2 changed files with 61 additions and 0 deletions

View File

@@ -1544,4 +1544,40 @@ public class MapUtil {
}
return list;
}
/**
* 递归调用将多层级Map处理为一个层级Map类型
*
* @param map 入参Map
* @param flatMap 单层级Map返回值
* @param <K> 键类型
* @param <V> 值类型
*/
private static <K, V> void flatten(Map<K, V> map, Map<K, V> flatMap) {
for (Map.Entry<K, V> entry : map.entrySet()) {
K key = entry.getKey();
V value = entry.getValue();
if (value instanceof Map) {
flatten((Map<K, V>) value, flatMap);
} else {
flatMap.put(key, value);
}
}
}
/**
* 将多层级Map处理为一个层级Map类型
*
* @param map 入参Map
* @return 单层级Map返回值
* @param <K> 键类型
* @param <V> 值类型
*/
public static <K, V> Map<K, V> flatten(Map<K, V> map) {
Assert.notNull(map);
Map<K, V> flatMap = new HashMap<>();
flatten(map, flatMap);
return flatMap;
}
}

View File

@@ -862,4 +862,29 @@ public class MapUtilTest {
assertEquals(0, MapUtil.get(map, "age", new TypeReference<Integer>() {
}, 0));
}
@Test
public void flattenMapReturnsTest() {
Map<String, String> clothes = new HashMap<>();
clothes.put("clothesName", "ANTA");
clothes.put("clothesPrice", "200");
Map<String, Object> person = new HashMap<>();
person.put("personName", "XXXX");
person.put("clothes", clothes);
Map<String, Object> map = new HashMap<>();
map.put("home", "AAA");
map.put("person", person);
Map<String, Object> flattenMap = MapUtil.flatten(map);
assertEquals("ANTA", MapUtil.get(flattenMap, "clothesName", new TypeReference<String>() {
}));
assertEquals("200", MapUtil.get(flattenMap, "clothesPrice", new TypeReference<String>() {
}));
assertEquals("XXXX", MapUtil.get(flattenMap, "personName", new TypeReference<String>() {
}));
assertEquals("AAA", MapUtil.get(flattenMap, "home", new TypeReference<String>() {
}));
}
}