Java - Stream Stream Operations

Introduction

A stream supports two types of operations:

  • Intermediate operations
  • Terminal operations

Intermediate operations are known as lazy operations.

Terminal operations are known as eager operations.

A lazy operation on a stream does not process the elements until another eager(Terminal) operation is called on the stream.

An intermediate operation on a stream produces another stream.

Stream processing does not start until a terminal operation is called.

You must use a terminal operation on a stream for it to process the data to produce a result.

The terminal operation is called a result-bearing operation and intermediate operations are called non result-bearing operations.

The following code uses a pipeline of stream operations to compute the sum of odd integers from 1 to 5:

Demo

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    int sum = numbers.stream()
                     .filter(n -> n % 2 == 1)
                     .map(n -> n * n)
                     .reduce(0, Integer::sum);

    System.out.println(sum);//from   w  w w. ja v a  2s.  co  m
  }
}

Result

Related Topics