December 11, 2019

What are Java Streams?

A Java Stream can be considered as a pipeline of data. It is basically an operation that runs on a sequence of data to produce a result just like an assembly line in a factory.

Assembly line model for car manufacturing.

Above image represents a car manufacturing model in which the car undergoes different processes at each step. As soon as car-1 finishes step 1, car-2(which was waiting on the line) will be submitted for step-1.

Similar to this Java streams are functions on a list of data. The data can undergo specific operations at each level.

Java Stream example :

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

public class MainClass {
	public static void main(String args[]) {
		List<String> list = Arrays.asList("a","2","b","c","3","d");
		list.stream()
		.filter(letter->isAlpha(letter))
		.map(alpha->alpha.toUpperCase())
		.forEach(letter->System.out.println(letter));
	}
	
	private static boolean isAlpha(String str) {
		char let = str.charAt(0);
		return (let>='A' && let<='Z') || (let>='a' && let<='z'); 
	}
}

The above code :

  1. Filters alphabets from a list of letters
  2. Transform each alphabet to its uppercase
  3. iterate over the result and print the result

Leave a Reply

Your email address will not be published. Required fields are marked *