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

Suppose we were given the following two arrays

String[] keys = new String[] {"a", "b", "c", "aa", "d", "b"} int[] values = new int[] { 1 , 2 , 3 , 4 , 5 , 6 } 

And combining these 2 arrays in a HashTable, we get the following

 // pseudo-code Map<String, Integer> dictionary = new HashTable<>( ("a" => 1) ("b" => 8) // because "b" appeared in index 1 and 5 ("c" => 3) ("aa" => 4) ("d" => 5) ); 

How can we do this using java style lambda?

So far I have the following:

 // this loops through the range given (used for index start and end) // and sums the values of duplicated keys tree.listMap = IntStream.range(range[0], range[1]).boxed().collect( Collectors.toMap(i - > dictionary[i], i - > i + 1, Integer::sum, TreeMap::new) ); 

However, I would like to take 2 arrays, combine them by key and value, where value is the sum of all values ​​for duplicated keys. How can we do this?

+6
source share
2 answers

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 very similar to the snippet you posted, although for some reason you posted a snippet that does not contain references to the keys and values arrays.

+6
source

I don't like to use streams when accessing indexes, but you can use groupingBy and summingInt to achieve 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 under the assumption that the keys and values ​​are the same length, so you can perform an additional check.

+3
source

Source: https://habr.com/ru/post/1272904/


All Articles