diff --git a/continew-starter-core/src/main/java/top/continew/starter/core/util/MapUtils.java b/continew-starter-core/src/main/java/top/continew/starter/core/util/MapUtils.java index 0c0376c8..f9c15f76 100644 --- a/continew-starter-core/src/main/java/top/continew/starter/core/util/MapUtils.java +++ b/continew-starter-core/src/main/java/top/continew/starter/core/util/MapUtils.java @@ -16,8 +16,9 @@ package top.continew.starter.core.util; -import java.util.Map; -import java.util.Properties; +import cn.hutool.core.map.MapUtil; + +import java.util.*; /** * Map 工具类 @@ -41,4 +42,50 @@ public class MapUtils { properties.putAll(source); return properties; } + + /** + * 深度合并两个map + * 需要用新的map接收 + * + * @param to 需要合并的map + * @param from 需要被合并的map + * @return Map 必须重新使用的map + * @author luoqiz + * @since 2.14.0 + */ + public static Map mergeMap(Map to, Map from) { + if (MapUtil.isEmpty(to)) { + return from; + } + if (MapUtil.isEmpty(from)) { + return to; + } + if (MapUtil.isEmpty(to) && MapUtil.isEmpty(from)) { + return new HashMap<>(); + } + Set> entries = to.entrySet(); + Iterator> iterator = entries.iterator(); + while (iterator.hasNext()) { + Map.Entry kv = iterator.next(); + String toKey = kv.getKey(); + Object toValue = kv.getValue(); + Object fromValue = from.get(toKey); + if (fromValue != null) { + if (toValue instanceof Map) { + Map childTo = (Map)toValue; + mergeMap(childTo, (Map)fromValue); + } else { + to.put(toKey, fromValue); + } + } + } + + Set keys = from.keySet(); + for (String key : keys) { + if (!to.containsKey(key)) { + to.put(key, from.get(key)); + } + } + return to; + } }