Stream API
Stream API is introduced in java 1.8 and the method stream() is a default method in Collection interface.
Once you work on the stream, you can't reuse it. It will throw an IllegalStateException.
Advantages of Stream API:
1. Stream is fast compared to normal collections. and It is an internal process. 2. Stream make sure that you can use multiple threads to work on your data 3. It also make sure that you don't change the existing data 4. Stream has certain use cases. So whenever we have huge amount of data which we want to process then we will use stream.
Parallel Stream: if you want to work with multiple threads behind the scene then we need to use parallel stream where as stream will use single thread. If the values are dependent on the other values there we cannot use parallel stream.
Example:
import java.util.ArrayList;
import java.util.stream.Stream;
public class Student {
int age;
String name;
String tech;
public Student(int age, String name, String tech) {
this.age=age;
this.name=name;
this.tech=tech;
}
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + ", tech=" + tech + "]";
}
}
public class StreamExmp {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Student> al =new ArrayList<Student>();
al.add(new Student(10,"Chandu","java"));
al.add(new Student(9, "Aswin","python"));
al.add(new Student(26,"Sachin","SQL"));
al.add(new Student(38,"Siva","java"));
al.stream().filter(s->s.tech.equals("java")).forEach(s->System.out.println(s));
}
Comments
Post a Comment