Java – Stream Processing

A Stream object’s processing can be sequential or parallel.

  • In a sequential mode, the elements are processed in the order of the source of the Stream.
  • The parallel mode allows the use of multiple threads on multiple cores but there is no guarantee of the order in which elements are processed.

package com.pwn.stream;

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

public class StreamProcessing {

	public static void main(String[] args) {
		List<Integer> integerList = Arrays.asList(0, 1, 2, 3, 4, 5);
		System.out.println(
				"***********Sequential Processing***********");

		integerList.stream().filter(p -> (p % 2) == 0)
				.forEach(System.out::println);

		System.out
				.println("***********Parallel Processing***********");

		integerList.parallelStream().filter(p -> (p % 2) == 0)
				.forEach(System.out::println);
	}

}

***********Sequential Processing***********
0
2
4
***********Parallel Processing***********
4
2
0

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s