Streams

reduce example

Given we have a set of strings mapped to some certain integer values:

Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 5);
map.put("C", 10);

When we receive a inputString consisting of strings from the map, then we need to return a sum of integers corresponding to each string in the map:

return Arrays.stream(inputString.split(""))
                .reduce(0,
                        (partialSum, element) -> partialSum + dictionary.get(element),
                        Integer::sum);

As we can see from the example, if we use reduce, the solution can be very compact:

  1. inputString.split("") transforms intupString into an array of strings.
  2. Arrays.stream() creates a stream out of the array of strings.
  3. reduce calculates a sum of the integers corresponding to each string element from the stream: 3.1. 0 is the identity value, that is the value we start our calculations from. 3.2. (partialSum, element) -> partialSum + dictionary.get(element) is the accumulator function. 3.3. Integer::sum is the combiner function.

Java documentation: reduce