Streams in Java 8
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>();
productList.add(1000);
for (int i = 0; i < 6; i++) {
int lastvalue = productList.get(i);
productList.add(lastvalue+1000);
}
System.out.println("Input List --> "+productList);
List serialList = new ArrayList();
productList.stream().filter(p->p>3000).forEach(s->{
System.out.println("Thread Name --> "+Thread.currentThread().getName());
serialList.add(s);
});
System.out.println("Serial Stream --> "+serialList);
List parallelList = new ArrayList();
productList.parallelStream().filter(p->p>3000).forEach(s->{
System.out.println("Thread Name --> "+Thread.currentThread().getName());
parallelList.add(s);
});
System.out.println("Parallel Stream --> "+parallelList);
}
}
Output:-
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
Terminal
Intermediate Operations:-
it will return a new stream always.
Statefull(Maintain whether visited or not) and stateless
It is lazy
Terminal Operations:-
it is eager.
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().