@tskuzzy 和@Peter 在这里的回答稍有即兴发挥。StrangeHashMap
只需通过扩展来定义自己的HashMap
.
public class StrangeHashMap extends HashMap<String, String> {
@Override
public String put(String key, String value) {
if(this.containsKey(key)) {
return super.put(key, super.get(key) + value);
} else {
return super.put(key, value);
}
}
}
你可以这样使用它:
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "Value1");
map1.put("key2", "Value2");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("key1", "Value2");
map2.put("key3", "Value3");
Map<String, String> all = new StrangeHashMap();
all.putAll(map1);
all.putAll(map2);
System.out.println(all);
以上为我打印以下内容:
{key3=Value3, key2=Value2, key1=Value1Value2}