How to merge two arrays into a map using Java streams?

There you go:

Map<String,Integer> themap = 
       IntStream.range (0, keys.length).boxed()
                .collect (Collectors.toMap(i->keys[i],
                                           i->values[i],
                                           Integer::sum,
                                           TreeMap::new));

Output:

{a=1, aa=4, b=8, c=3, d=5}

This is quite similar to the snippet you posted, though, for some reason, the snippet you posted contains no reference to the keys and values arrays.


I don't like using streams when referring to indexes, but you can use groupingBy and summingInt to accomplish this:

Map<String, Integer> result = IntStream.range(0, keys.length)
   .boxed()
   .collect(
       Collectors.groupingBy(
           i -> keys[i],
           Collectors.summingInt(i -> values[i])
       )
   );

Note that this works on the assumption that keys and values are both of equal length, so you may want to do some additional validation.