简体   繁体   English

如何使用泛型结合两个包含相同类型的HashMap对象,并控制重复的情况

[英]How can I combine two HashMap objects containing the same types using Generics and control what happens in case of duplicates

java-如何使用泛型有效合并两个包含相同类型的Map对象,并控制重复的情况(如果值是Integer则加或乘,如果值是String则Concat)时会发生什么?

Add the elements of one map to the other one at a time using Map.merge : 使用Map.merge一次将一个地图的元素添加到另一地图中:

for (Map.Entry<K, V> entry : map2.entrySet()) {
  map1.merge(entry.getKey(), entry.getValue(), (oldV, newV) -> /* some expression to combine old and new values */);
}

If you are using Java 7 or earlier, the above linked documentation shows how you can implement it without Java 8 features (in the "Implementation Requirements" section). 如果您使用的是Java 7或更早版本,则以上链接的文档说明了如何在没有Java 8功能的情况下实现它(在“实施要求”部分中)。

You can try like below example: 您可以尝试以下示例:

Map<String, Integer> map1 = new HashMap<>();
map1.put("Java", 7);
map1.put("C#", 4);
Map<String, Integer> map2 = new HashMap<>();
map2.put("Java", 3);
map1.put("Scala", 5);

map1.keySet().forEach(e -> {
    map2.computeIfPresent(e, (String key,Integer value)-> value+map1.get(key));
    map2.putIfAbsent(e, map1.get(e));
});

System.out.println(map2);

EDIT: If you want to handle all of your use cases then you can do like below. 编辑:如果您想处理所有用例,则可以执行以下操作。

Map<String, Object> map1 = new HashMap<>();
map1.put("Java", 7);
map1.put("C#", 4);
Map<String, Object> map2 = new HashMap<>();
map2.put("Java", 3);
map1.put("Scala", 5);

map1.keySet().forEach(e -> {
    map2.computeIfPresent(e, (String key, Object value) -> {
        if (value instanceof Integer)
            return Integer.sum((Integer) value, (Integer) map1.get(key));
        if (value instanceof String) {
            String s1 = (String) value;
            String s2 = (String) map1.get(key);
            return s1.concat(s2);
        }
        return null;
    });
    map2.putIfAbsent(e, map1.get(e));
});

System.out.println(map2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM