java – Merge two maps with Java 8 API Stream

mx =,
        (a, b) -> b.forEach((k, v) -> a.merge(k, v, Integer::max)),

This covers the general case for any size list and should work with any type, just swap the Integer::max and / or HashMap::new as desired.

If you don’t care what value emerges in a merge, there is a much cleaner solution:

mx =, Map::putAll, Map::putAll);

And as generic methods:

public static <K, V> Map<K, V> mergeMaps(Stream<? extends Map<K, V>> stream) {
    return stream.collect(HashMap::new, Map::putAll, Map::putAll);

public static <K, V, M extends Map<K, V>> M mergeMaps(Stream<? extends Map<K, V>> stream,
        BinaryOperator<V> mergeFunction, Supplier<M> mapSupplier) {
    return stream.collect(mapSupplier,
            (a, b) -> b.forEach((k, v) -> a.merge(k, v, mergeFunction)),

Leave a comment