- reduce operation on stream provides a way to accumulate the result of an operation which traverses all items in the stream.
- The traversal starts from the leftmost item in the stream.
- There are three implementations of the reduce operation.
- The first implementation uses the first item in the stream as initial accumulator.
- The second implementation expects an initial accumulator input.
- The third implementation provides a way to return an accumulator which has a different type from the stream items. This is similar to foldLeft in other functional languages e.g. Scala.
int stream one to three
IntStream oneToThree = IntStream.of(1, 2, 3);
int stream one to two
string stream
USAGE
IntStream oneToTwo = IntStream.of(1, 2);
string stream
Stream stringStream = Stream.of("a", "ab", "abc", "abcd");
USAGE
log.info("first implementation - reducing oneToThree Integer stream by addition: " +
oneToThree.reduce((acc, item) ->
acc+item
)
);
log.info("second implementation - reducing oneToTwo Integer stream by addition starting " +
"with an initial accumulator of 10: " +
oneToTwo.reduce(10, (acc, item) ->
acc+item
)
);
log.info("third implementation - reducing stringStream to a list of Integer containing the count of each string in the stream :" +
stringStream.reduce( //the initial output new ArrayList<Integer>(), //accumulating into the initial output (acc, item) -> { acc.add(item.length()); return acc; }, // combining the output // (needed only for parallel stream) (acc1, acc2) -> acc1 ) );
Comments
Post a comment