Stream API of Java
1. Stream API
Introduced in Java 8.
Provides a functional approach to processing collections of objects.
2. Features of Java Stream
It does not store element. It only conveys elements from a source through a pipeline of computational operations.
It is lazy and evaluates code only when required.
It has three main parts, Source, Intermediate Operation and Terminal Operation
Where :
Source can be a data structure, an array, etc.
Intermediate Operation can be a pipelined operations which is lazily executed and returns a stream as a result.
Terminal Operation can be an operation which starts the internal pipeline operations and returns a non-stream as a result.
3. List of Intermediate Operations
filter
map
flatmap
sorted
peek
distinct
limit
skip
Example:
map : It is used to map the items in the collection to other objects according to the function passed as argument.
List number = Arrays.asList(1,2,3,4,5);
List square = number.stream().map(n -> n*n).collect(Collectors.toList());
filter : It is used to select element as per the Predicate passed as argument.
List names = Arrays.asList("Terminal Operation","Immediate Operation","Source");
List result = names.stream().filter(n->n.startsWith("S")).collect(Collectors.toList());
sorted : It is used to sort the Stream
List names = Arrays.asList("Terminal Operation","Immediate Operation","Source");
List result = names.stream().sorted().collect(Collectors.toList());
4. List of Terminal Operations
forEach
forEachOrdered
toArray
reduce
collect
min
max
count
anyMatch
allMatch
noneMatch
findFirst
findAny
Example :
collect : It is used to return the result of the Intermediate Operations performed on the stream.
List number = Arrays.asList(1,2,3,4,5);
Set square = number.stream().map(n->n*n).collect(Collectors.toSet());
forEach : It is used to iterate through every element of the stream.
List number = Arrays.asList(1,2,3,4,5);
number.stream().map(n->n*n).forEach(r->System.out.println(r));
count : It is used to count the number of elements of the stream.
List number = Arrays.asList(1,2,3,4,5);
long count = number.stream().count();
Ref :
http://tutorials.jenkov.com/java-functional-programming/streams.html
https://www.javatpoint.com/java-8-stream
https://www.geeksforgeeks.org/stream-in-java/
Comments