Link

Introduction to Streams

Table of contents

  1. Streams

Streams

Java 8 introduced streams, which can ve visualised as a pipeline through which data can pass through.

Pipeline (Reference)

Streams comprise three parts.

  1. Source
  2. A number of Intermediate Operations
  3. A Terminal Operation

Stream Parts.png

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.

  1. It starts with a source of Strings

    Stream.of( "1", "2", "3", "4" )
    
  2. Then performs several intermediate operations

    1. Converts the String to int

        .mapToInt( Integer::parseInt )
      
    2. Removes the odd numbers

        .filter( App::isEvenNumber )
      
    3. Doubles the numbers

        map( App::doubleNumber )
      
  3. Finally, it performs a terminal operation which sums all numbers

    .sum()