java - 在 HashMap Java8 中传递用户定义的合并行为方法

标签 java merge java-8 hashmap

我想提供用户定义的方法来合并 java 8 中的 map ?您创建的方法应该接受两个映射和“合并”行为。

 public <T> Map<? super T, ? super T> mergeMaps( Map<? super T, ? super 
 T> map1, Map<? super T, ? super T> map2 ) {
 // merging code here
 }

但是我想要这样的东西

public <T> Map<? super T, ? super T> mergeMaps( Map<? super T, ? super T> 
map1, Map<? super T, ? super T> map2 , MergeTwoMaps<T, U> mergeTwoMaps) 
{
    // merging code here
}

是这样的。 Java generic merge

 Map<String, Integer> map1 = new HashMap<>();
 Map<String, Integer> map2 = new HashMap<>();
 map1.put(“key1”, 20);
 map1.put(“key2”, 30);
 map2.put(“key3”, 40);
 map2.put(“key1”, 50);

mergeMaps(map1,map2,mergeBehaviour)
Output should be
map.get("key1")--> 70

Map<String, String> map1 = new HashMap<>();
 Map<String, String> map2 = new HashMap<>();
 map1.put(“key1”, "Hello");
 map1.put(“key2”, "Hi");
 map2.put(“key3”, "Ok");
 map2.put(“key1”, "world");
 mergeMaps(map1,map2,mergeBehaviour)

 Output should be
 map.get("key1")--> Helloworld

最佳答案

您应该重新考虑您想要的方法签名。引用the guidelines :

Using a wildcard as a return type should be avoided because it forces programmers using the code to deal with wildcards.

换句话说,在返回类型中包含通配符会强制调用者使用返回结果将通配符散布到每个代码中。

该方法应该看起来像:

public static <K, V> Map<K, V> mergeMaps(
    Map<? extends K, ? extends V> map1, Map<? extends K, ? extends V> map2,
    BinaryOperator<V> mergeFunction) {

    Map<K, V> result = new HashMap<>(map1);
    map2.forEach((k,v) -> result.merge(k, v, mergeFunction));
    return result;
}

它允许调用者选择任意键和值类型,只要输入参数兼容,如果输入映射的键和值类型与输出映射或其子类型相同,情况总是如此。当然,这个签名也允许键和值类型相同的用例,但它不是必需的。

合并操作的实现本身很简单。

您可以通过使用进一步提高方法的灵 active

public static <K, V> Map<K, V> mergeMaps(
    Map<? extends K, ? extends V> map1, Map<? extends K, ? extends V> map2,
    BiFunction<? super V, ? super V, ? extends V> mergeFunction) {

    Map<K, V> result = new HashMap<>(map1);
    map2.forEach((k,v) -> result.merge(k, v, mergeFunction));
    return result;
}

虽然这很少需要,因为在传递方法引用或 lambda 表达式时它是不必要的。这仅在重用已存在的 BiFunction 实例时有用。

关于java - 在 HashMap Java8 中传递用户定义的合并行为方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56250842/

相关文章:

java - 按属性属性选择 Realm

git - 因 merge 冲突而重新建立基础 : How to undo?

java - 如何使用 typescript 中的属性对对象数组进行分组?

python - 在python中连接数据框时如何分配新的描述性列

git pull 到 branch_1 并同时 merge 到当前分支

java - 在Java中进行远程调用时要处理哪些异常

java - 在所有列上解析 Array_agg

java - 从 webview 返回到 Activity

java - JxBrowser 还要多久才能发布最新版本的 Chromium(版本 77)?

java - Java 中的面向方面编程