JAVA : Why use Java Stream ?

I love learning about technology and sharing that with others
Motivation
Understanding why we should use Streams over conventional for loop is critical and it can easily ramp up your coding game.
Problem Statement
- list of employee with id,name and salary
- get all the employee whose salary is above 15
- store it in separate list and print it
Conventional Way of Doing
- Traverse List
- Write if and filter on that
- Store it in separate list
- Print separate list
Code
for( Employee e:empList) {
if(e.getSal()>15) {
richGuys.add(e);
}
}
Sysout.out.println(richGuys);
Do this with Stream
List<Employee> richGuys=empList.stream()
.filter(e -> e.getSal()>15)
.collect(Collectors.toList());
here we have used filter method and given the method to it that how we wants to filter and then we have used collect method to produce the list out of that stream
- There are bunch of other method in stream and we can combine the methods of stream
Example
filter and sorted --> first filter with sal > 15 and then sort with the salary
List<Employee> richGuysSorted=empList.stream()
.filter(e -> e.getSal()>15)
.sorted(Comparator.comparing(employee -> employee.getSal()))
.collect(Collectors.toList());
Streams will not modify the original list or data structure

