Java 8 - Streams API

Streams API:
* stream() method present inside collection interface as default method.
* Stream is a interface present in java.util.stream package.
* Stream s = c.stream(); // c - any collection object
Use of Stream:
* If you want to perform some operation in collection, then will go for Steams.

Filter:
* If you want to filter the collection object based on some boolean condition, then we have to go for this.

public stream filter(Predicate<T> t){

}

Processing stream involved in 2 steps,
1. Configureation
a. filter  - If you want to filter the collection object then we have to go for this.
b. map - If you want to perform some operation using this all values, then we have to go for this.
2. Processing

How to use,

Print Even Numbers:

ArrayList<Integer> l = new ArrayList<>();
l.add(0);
l.add(5);
l.add(10);
l.add(15);
l.add(20);
l.add(25);
Example 1:  For Filter
* If you want to filter the collection object based on some boolean condition, then we have to go for this.
* Filter method is available in the Stream interface.
Syntax:
public stream filter(Predicate<T> t){

}
Java 7:
ArrayList<Integer> l2 = new ArrayList<>();
for(Integer I1 : l){
if(I1 % == 0){
l2.add(I1);
}
}
System.out.println(l2);

Java 8: With Streams

List<Integer> l2 = l.stream().filter()(I -> I%2 ==0).collect(Collectors.toList());
System.out.println(l2);

Example 2: For Map
* If you want to create seperate new object, every object present on the input collection to perform some operation using this all values, then we have to go for this.
* Map method is available in the Stream interface.
Syntax:
public stream map(Predicate<T,R> f){

}
Java 7:
ArrayList<Integer> l2 = new ArrayList<>();
for(Integer I1 : l){
l2.add(I1*2);
}
System.out.println(l2);

Java 8: With Streams

List<Integer> l2 = l.stream().map(I -> I*2).collect(Collectors.toList());
System.out.println(l2);

Comments

Popular posts from this blog

How to set Java Object into JaxBElement ?

GitLab