Reducing Streams in Java

Java 8 introduced streams, among other things, and one of my favourite features is the reduce() method. It combines a stream into a single method.

Before Java 8 and streams, such a reduction had to be done with a loop like this:

String[] array = new String[] { "h", "e", "l", "l", "o" };
String concatenated = "";
for (String s : array) {
    concatenated = concatenated + s;
}

Now with Streams and reduce() it can be done as follows with a method reference:

Stream<String> stream = Stream.of("h", "e", "l", "l", "o"); 
String concatenated = stream.reduce("", String::concat);

Or more verbose with lambda:

Stream<String> stream = Stream.of("h", "e", "l", "l", "o"); 
String concatenated = stream.reduce("", (s, c) -> s + c);

Here is another example of reduction:

BinaryOperator<Integer> multiplication = (a, b) -> a * b;
Stream<Integer> integersStream = Stream.of(1, 2, 3, 4, 5);
integersStream.reduce(multiplication).ifPresent(System.out::print);

In this example we are applying a binary operation for multiplication on a stream of integers from 1 to 5. Depending on the input stream, this reduction may be null and that’s why we use ifPresent() to print it if it is available.

Comments

So empty here ... leave a comment!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Sidebar



%d bloggers like this: