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 <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)),
            Map::putAll);
}

Leave a comment