java – Merge two maps with Java 8 API Stream

mx = list.stream().collect(HashMap::new,
        (a, b) -> b.forEach((k, v) -> a.merge(k, v, Integer::max)),
        Map::putAll);

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 = list.stream().collect(HashMap::new, 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)),
            Map::putAll);
}

Leave a comment