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  Map mergeMaps(Stream> stream) {
    return stream.collect(HashMap::new, Map::putAll, Map::putAll);

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

Leave a comment