Introduction to Streams
Table of contents
Streams
Java 8 introduced streams, which can ve visualised as a pipeline through which data can pass through.
Streams comprise three parts.
- Source
- A number of Intermediate Operations
- A Terminal Operation
Consider the following example
package demo;
import java.util.stream.Stream;
public class App {
public static void main( final String[] args ) {
final int sum = Stream.of( "1", "2", "3", "4" )
.mapToInt( Integer::parseInt )
.filter( App::isEvenNumber )
.map( App::doubleNumber )
.sum();
System.out.printf( "The sum is %d%n", sum );
}
private static int doubleNumber( final int number ) {
return number * 2;
}
private static boolean isEvenNumber( final int number ) {
return number % 2 == 0;
}
}
The above example makes use of streams.
It starts with a source of Strings
Stream.of( "1", "2", "3", "4" )
Then performs several intermediate operations
Converts the
String
toint
.mapToInt( Integer::parseInt )
Removes the odd numbers
.filter( App::isEvenNumber )
Doubles the numbers
map( App::doubleNumber )
Finally, it performs a terminal operation which sums all numbers
.sum()