简体   繁体   English

Java:编写通用HashMap合并方法的正确方法是什么?

[英]Java: What's the right way of writing a generic HashMap merge method?

This is probably a basic Java question but I somehow can't find the right keywords to google for the right solution. 这可能是一个基本的Java问题,但是我不知何故找不到适合Google的正确解决方案的关键字。

I have several pairs of HashMap objects and I need to merge each respective pair in a straightforward ways: if two keys match, add up the two values and store the sum in the first map. 我有几对HashMap对象,我需要以一种简单明了的方式合并每对对象:如果两个键匹配,则将两个值相加并将其和存储在第一张地图中。 So I might have something like: 所以我可能会有类似的东西:

HashMap<String,Double> mapSD1, mapSD2;
HashMap<String,Integer> mapSI1, mapSI2;
HashMap<MyClassA,Float> mapCF1, mapCF2;

What is the right way of writing a generic mergeMaps methods that can merge all these types, instead of having 3 more or less identical methods for each type? 编写可合并所有这些类型的通用mergeMaps方法的正确方法是什么,而不是每种类型都具有3个或多或少相同的方法?

There is no generic way to add numbers of different types. 没有通用的方法可以添加不同类型的数字。 You would have to tell the method how to add to Float values, two Integer values etc. 您将不得不告诉该方法如何将Float值,两个Integer值等相加。

Since you are using Java 7, you will have to prepare some ground first. 由于您使用的是Java 7,因此必须首先准备一些基础知识。 You could create the following interface: 您可以创建以下界面:

public interface BinaryOperator<T> {

    T apply(T t1, T t2);
}

Then you could do: 然后,您可以执行以下操作:

private static final BinaryOperator<Float> ADD_FLOATS = new BinaryOperator<Float>() {
    @Override
    public Float apply(Float t1, Float t2) {
        return t1 + t2;
    }
};

public static <K, V> void merge(Map<K, V> map1, Map<K, V> map2, BinaryOperator<V> op) {
    for (Map.Entry<K, V> e : map2.entrySet()) {
        V val = map1.get(e.getKey());
        if (val == null) {
            map1.put(e.getKey(), e.getValue());
        } else {
            map1.put(e.getKey(), op.apply(val, e.getValue()));
        }
    }
}

public static void main(String[] args) {
    Map<String, Float> map = new HashMap<>();
    map.put("A", 1.2F);
    map.put("B", 3.4F);
    Map<String, Float> map2 = new HashMap<>();
    map2.put("B", 5.6F);
    map2.put("C", 7.8F);
    merge(map, map2, ADD_FLOATS);
    System.out.println(map);   // prints {A=1.2, B=9.0, C=7.8}
}

When you upgrade to Java 8 you will be able to get rid of BinaryOperator (it's already there), and there would be no need to create ADD_FLOATS . 升级到Java 8后,您将可以摆脱BinaryOperator (已经存在)了,并且无需创建ADD_FLOATS You will be able to just do 您将能够做到

merge(map, map2, Float::sum);

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

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