Notes on Stream :
- The main goal of the Stream API is to make collection easier, also many times it helps in better performance.
- A stream is not a data structure to store any elements it transfers from a data structure like an array through a pipeline of operations.
- It is functional in nature, does not modify the source.
- The elements of a stream are visited only once like an iterator, to revisit we need to generate a new stream.
- To create Stream we can use stream() method of Stream class in java.
- 3 most used Stream methods are filter(), map(), reduce().
Parallel Stream java 8:
If we have large number of data to handle we can use parallelStream (.parallelStream() in place of .stream()). Parallel stream() works on all the cores instead of 1 core in the serial stream.Operations on Stream :
There are 2 types of operation in Stream :
Intermediate Operation :
These operations return a stream, hence we can use other methods in the stream to get another stream as a result.
In this way, it is possible to use a chain of methods.
Example -> filter(), map(), sorted().
Terminal Operations:
These operations return a values of a certain type.
Example For each (),count(), collect().
Find all even number squares of an array and put it in a set using Stream API
Here is an example of same.
public class Test {
public static void main(String... args) {
Integer [] arr = {1,2,3,4,5};
Set set = new HashSet<>();
set = Arrays.asList(arr)
.stream().filter(x ->( x%2==0)) //Filter Even Numbers
.map(x->Math.pow(x, 2)) //Square the numbers
.peek(System.out::println) //print without termination
.collect(Collectors.toSet()); // Collect to a Set
}
}
1 comments:
Click here for commentsI constantly emailed this site post page to all my friends, because if prefer to read it then my all friends will too.
ConversionConversion EmoticonEmoticon