MapUtil增加flatten方法(pr#1368@Gitee)

This commit is contained in:
Looly
2025-07-30 19:10:12 +08:00
parent 6760658cba
commit 4dcbc74cd1
2 changed files with 30 additions and 25 deletions

View File

@@ -8,7 +8,8 @@
* 【captcha】 `MathGenerator`四则运算方式支持不生成负数结果pr#1363@Gitee * 【captcha】 `MathGenerator`四则运算方式支持不生成负数结果pr#1363@Gitee
* 【core 】 增加`MapValueProvider``RecordConverter`并支持Record转换issue#3985@Github * 【core 】 增加`MapValueProvider``RecordConverter`并支持Record转换issue#3985@Github
* 【core 】 `CalendarUtil`增加`isSameYear``calendar`方法issue#3995@Github * 【core 】 `CalendarUtil`增加`isSameYear``calendar`方法issue#3995@Github
* 【core 】 `DateUtil`新增方法`yyyy-MM-dd'T'HH:mmXXX`格式支持pr#1367@Gitee * 【core 】 `DateUtil`增加`yyyy-MM-dd'T'HH:mmXXX`格式支持pr#1367@Gitee
* 【core 】 `MapUtil`增加flatten方法pr#1368@Gitee
### 🐞Bug修复 ### 🐞Bug修复
* 【extra 】 `Sftp``reconnectIfTimeout`方法改为捕获所有异常issue#3989@Github * 【extra 】 `Sftp``reconnectIfTimeout`方法改为捕获所有异常issue#3989@Github

View File

@@ -1545,27 +1545,6 @@ public class MapUtil {
return list; 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类型 * 将多层级Map处理为一个层级Map类型
* *
@@ -1574,10 +1553,35 @@ public class MapUtil {
* @param <K> 键类型 * @param <K> 键类型
* @param <V> 值类型 * @param <V> 值类型
*/ */
public static <K, V> Map<K, V> flatten(Map<K, V> map) { public static <K, V> Map<K, V> flatten(final Map<K, V> map) {
return flatten(map, new HashMap<>());
}
/**
* 递归调用将多层级Map处理为一个层级Map类型
*
* @param map 入参Map
* @param flatMap 单层级Map返回值
* @param <K> 键类型
* @param <V> 值类型
* @return 单层级Map返回值
*/
@SuppressWarnings("unchecked")
public static <K, V> Map<K, V> flatten(final Map<K, V> map, Map<K, V> flatMap) {
Assert.notNull(map); Assert.notNull(map);
Map<K, V> flatMap = new HashMap<>(); if(null == flatMap){
flatten(map, flatMap); flatMap = new HashMap<>();
}
Map<K, V> finalFlatMap = flatMap;
map.forEach((k, v) -> {
if (v instanceof Map) {
flatten((Map<K, V>) v, finalFlatMap);
} else {
finalFlatMap.put(k, v);
}
});
return flatMap; return flatMap;
} }
} }