Java tutorial
//package com.java2s; //License from project: Open Source License import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.function.BinaryOperator; public class Main { /** * Combines 2 maps by just adding the values of the same key together. * * @param a A map * @param b Another map * @param combiner The combiner of the values * @param <K> The type of the keys * @param <V> The type of the values * * @return a map that contains all the key of map a and b and the combined values. */ public static <K, V> Map<K, V> combine(Map<? extends K, ? extends V> a, Map<? extends K, ? extends V> b, BinaryOperator<V> combiner) { Map<K, V> result = new HashMap<>(); for (Entry<? extends K, ? extends V> entry : a.entrySet()) { if (b.containsKey(entry.getKey())) result.put(entry.getKey(), combiner.apply(entry.getValue(), b.get(entry.getKey()))); else result.put(entry.getKey(), entry.getValue()); } b.entrySet().stream().filter(e -> !result.containsKey(e.getKey())) .forEach(e -> result.put(e.getKey(), e.getValue())); return result; } /** * Combines 2 maps by just adding the values of the same key together. * * @param a A map * @param b Another map * @param <K> The type of the keys * * @return a map that contains all the key of map a and b and the combined values. */ public static <K> Map<K, Integer> combine(Map<? extends K, Integer> a, Map<? extends K, Integer> b) { return combine(a, b, Integer::sum); } }