From 5ca34eebd1228b445d9882d0d2777affd4393bca Mon Sep 17 00:00:00 2001 From: luoqiz Date: Thu, 14 Aug 2025 10:33:29 +0800 Subject: [PATCH] =?UTF-8?q?feat(core):=20MapUtils=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=B7=B1=E5=BA=A6=E5=90=88=E5=B9=B6=E4=B8=A4=E4=B8=AAmap?= =?UTF-8?q?=E7=9A=84=E6=96=B9=E6=B3=95=20(#16)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../continew/starter/core/util/MapUtils.java | 51 ++++++++++++++++++- 1 file changed, 49 insertions(+), 2 deletions(-) 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; + } }