mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-08-18 20:38:02 +08:00
@@ -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;
|
||||
}
|
||||
}
|
||||
|
@@ -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>() {
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user