Friday, December 28, 2018

Java Streams

Streams are very popular feature in Java 8. Its another step in the direction of supporting functional programming in Java.
Streams are a way of accessing data from various data source. Data source can be an array, any java collection objects, I/O channel (like files, socket etc) or a generator function. One important thing is Streams are not data structure it doesn't store data, it just convey the data from data source.

Streams facilitate various computational operations like fetch, filter, sort, aggregate, search etc. in a efficient way. But all these operations produces a result while not changing its source.
Stream operations are of two types,  intermediate or terminal .Filter and map are examples of intermediate operation For each and reduce are terminal operation. Intermediate operation doesn't get executed instantly ,it creates a new stream. Only after terminal operation it get evaluated.

Intermediate operations are further divided into stateless or stateful. In case of stateless like filter or map no state of previous element is required. But in case of sateful eg: sort or distinct to process new element previous element details are necessary.

By default streams are executed sequential, Streams support parallelism also. So that the elements can be processed in parallel manner.  

Lets see some code.

package demo.streams;

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

public class StreamDemo {

public static void main (String args[])
String[] arr = {"python", "perl", "java", "java script", "c", "c++", "html", "sql"};
List<String> strList =  Arrays.asList(arr);
// steam creation
Stream<String> stream  =;
// sort the elements
// find first element starts with j
Stream<String> filteredStream => string.startsWith("j"));
// in first 4 element how many elements start with p
// map
// prepend hello begin of each string>"Hello "+str).forEach(System.out::println);
// close
// parallel Stream, count the number of letters
strList.parallelStream().map(str->str + "="+ str.length()).forEach(System.out::println);

No comments:

Post a Comment