Create Team Blog
Let's kick off a fresh team blog! Bring on the crew and let's get to publishing.

Streams in Java 8

Prabu Subra's photo
Prabu Subra
·Jul 16, 2018

Streams!!! A Java Interface to perform certain set of operations on bunch of items/data/elements serially or parallel.

It is a functional or declarative style of programming in java. streams doesn’t store any data with it so we can’t get a data by address or index.

Streams can be created on Collections, Arrays, or I/O resources.

Mode of Streams:-

The way of creation of initial stream will result 2 different streams. it can be Serial or Parallel.

Serial → streams()

it just work like for loop, one by one on single thread.

Parallel → parallelStream()

it will run on multiple threads import java.util.ArrayList; import java.util.List;

public class StreamsUnderstanding{

public static void main(String[] args) {
    List<Integer> productList = new ArrayList<Integer>();
    for (int i = 0; i < 6; i++) {
        int lastvalue = productList.get(i);

    System.out.println("Input List --> "+productList);

    List serialList = new ArrayList();
          System.out.println("Thread Name --> "+Thread.currentThread().getName());
    System.out.println("Serial Stream --> "+serialList);
    List parallelList = new ArrayList();
         System.out.println("Thread Name --> "+Thread.currentThread().getName());

     System.out.println("Parallel Stream --> "+parallelList);


Input List --> [1000, 2000, 3000, 4000, 5000, 6000, 7000]

  Thread Name --> main
  Thread Name --> main
  Thread Name --> main
  Thread Name --> main

Serial List --> [4000, 5000, 6000, 7000]

  Thread Name --> ForkJoinPool.commonPool-worker-3
  Thread Name --> ForkJoinPool.commonPool-worker-3
  Thread Name --> main
  Thread Name --> ForkJoinPool.commonPool-worker-2

Parallel List --> [5000, 4000, 6000, 7000]

Conversion of Streams:-

After the initial creation of Streams, it can be converted from Parallel to Sequential or vice versa..

  * sequential() - will convert Parallel stream to Serial Stream.
  * parallel() - will convert Serial stream to Parallel Stream.

Stream Operations:-


Intermediate Operations:-

it will return a new stream always.
Statefull(Maintain whether visited or not) and stateless
It is lazy

Terminal Operations:-

  1. it is eager.

  2. when the terminal operator is initiated stream pipeline will be executed sequentially or parallel.

Stream Pipeline:-

A stream pipeline consists of a source (such as a Collection, an array, a generator function, or an I/O channel); followed by zero or more intermediate operations such as Stream.filter or Stream.map; and a terminal operation such as Stream.forEach or Stream.reduce.


Short-Circuits in Streams:- Streams has couple of methods to disturb normal flow of intermediate and terminal operations. Examples:- limit(), findFirst(), findAny().