Search code examples
javamergehashmapjava-stream

Duplicate keys in Merged Map ignored


I've been trying to understand why the duplicate key function is not triggered when collecting the map, with no luck. I'm using Java SE 8 [1.8.0_141].

public static void main(String[] args) {

    Map<Long, Long> ts1 = new HashMap<Long, Long>();
    Map<Long, Long> ts2 = new HashMap<Long, Long>();

    ts1.put(0L, 2L);
    ts1.put(1L, 7L);
    ts2.put(2L, 2L);
    ts2.put(2L, 3L);


    Map<Long, Long> mergedMap = Stream.of(ts1, ts2)
            .flatMap(map -> map.entrySet().stream())
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (v1, v2) -> { 
                            System.out.println("Duplicate found");
                            return v1 + v2;}
                    ));

    mergedMap.entrySet().stream().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));

}

The result is

    0 2
    1 7
    2 3

I'm expecting

    0 2
    1 7
    2 5

Solution

  • When you do this:

    ts2.put(2L, 2L);
    ts2.put(2L, 3L);
    

    The 2nd put is overwriting the first one. So the ts2 map only contains one entry: the last one: (2L, 3L).

    So then, there's nothing to merge.