Merge map of arrays with duplicate keys : <p>I have two maps of arrays. </p>

<pre><code>Map&lt;String, List&lt;String&gt;&gt; map1 = new HashMap&lt;&gt;();
Map&lt;String, List&lt;String&gt;&gt; map2 = new HashMap&lt;&gt;();
</code></pre>

<p>I want to merge them in one new map.<br>
If a key exists in both maps, in that case, I should merge arrays. </p>

<p>For example:</p>

<pre><code>map1.put("k1", Arrays.asList("a0", "a1"));
map1.put("k2", Arrays.asList("b0", "b1"));

map2.put("k2", Arrays.asList("z1", "z2"));

// Expected output is 
Map 3: {k1=[a0, a1], k2=[b0, b1, z1, z2]}
</code></pre>

<p>I tried to do that with streams </p>

<pre><code>Map&lt;String, List&lt;String&gt;&gt; map3 = Stream.of(map1, map2)
    .flatMap(map -&gt; map.entrySet().stream())
    .collect(Collectors.toMap(
        Map.Entry::getKey,
        e -&gt; e.getValue().stream().collect(Collectors.toList())
    ));
</code></pre>

<p>This work if there are no the same keys in maps. Otherwise, I get the exception  </p>

<pre><code>Exception in thread "main" java.lang.IllegalStateException: Duplicate key k2 (attempted merging values [b0, b1] and [z1, z2])
    at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:133)
    at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:180)
    at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.base/java.util.HashMap$EntrySpliterator.forEachRemaining(HashMap.java:1751)
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
    at java.base/java.util.stream.ReferencePipeline$7$1.accept(ReferencePipeline.java:274)
    at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578)
    at im.djm.Test.main(Test.java:25)
</code></pre>

<p>Is there a way to accomplish this task with streams?<br>
Or I have to iterate throug maps? </p>
