1616
1717package top .continew .starter .core .util ;
1818
19- import java .util .Map ;
20- import java .util .Properties ;
19+ import cn .hutool .core .map .MapUtil ;
20+
21+ import java .util .*;
2122
2223/**
2324 * Map 工具类
@@ -41,4 +42,50 @@ public static Properties toProperties(Map<String, String> source) {
4142 properties .putAll (source );
4243 return properties ;
4344 }
45+
46+ /**
47+ * 深度合并两个map
48+ * 需要用新的map接收
49+ *
50+ * @param to 需要合并的map
51+ * @param from 需要被合并的map
52+ * @return Map<String, Object> 必须重新使用的map
53+ * @author luoqiz
54+ * @since 2.14.0
55+ */
56+ public static Map <String , Object > mergeMap (Map <String , Object > to , Map <String , Object > from ) {
57+ if (MapUtil .isEmpty (to )) {
58+ return from ;
59+ }
60+ if (MapUtil .isEmpty (from )) {
61+ return to ;
62+ }
63+ if (MapUtil .isEmpty (to ) && MapUtil .isEmpty (from )) {
64+ return new HashMap <>();
65+ }
66+ Set <Map .Entry <String , Object >> entries = to .entrySet ();
67+ Iterator <Map .Entry <String , Object >> iterator = entries .iterator ();
68+ while (iterator .hasNext ()) {
69+ Map .Entry <String , Object > kv = iterator .next ();
70+ String toKey = kv .getKey ();
71+ Object toValue = kv .getValue ();
72+ Object fromValue = from .get (toKey );
73+ if (fromValue != null ) {
74+ if (toValue instanceof Map ) {
75+ Map <String , Object > childTo = (Map <String , Object >)toValue ;
76+ mergeMap (childTo , (Map <String , Object >)fromValue );
77+ } else {
78+ to .put (toKey , fromValue );
79+ }
80+ }
81+ }
82+
83+ Set <String > keys = from .keySet ();
84+ for (String key : keys ) {
85+ if (!to .containsKey (key )) {
86+ to .put (key , from .get (key ));
87+ }
88+ }
89+ return to ;
90+ }
4491}
0 commit comments