Parallel and Sequential Stream in Java 8 Collection
April 27, 2014
Java 8 Collection has been enriched by stream methods. These methods are stream() and parallelStream() which are default methods and have been written in Collection interface. So that it will present in all implementing classes. With the help of these methods, we can write the code efficient. Old fashioned large number of line of code can be written in single liner of code. We see Parallel and Sequential Stream one by one with the example.
Parallel Stream
Collection.parallelStream() returns parallel stream instance for calling collection. The Stream object can be used for different purpose. In this example we have taken a list of employee which has salary field. For a given predicate, we will filter the list and then will calculate the average salary. Find the code below.ParallelStreamDemo.java
package com.concretepage.util.stream; import java.util.ArrayList; import java.util.List; import java.util.OptionalDouble; import java.util.function.Predicate; public class ParallelStreamDemo { public static void main(String[] args) { List<Employee> list = new ArrayList<>(); list.add(new Employee(1, "A", 2000)); list.add(new Employee(2, "B", 3000)); list.add(new Employee(3, "C", 4000)); list.add(new Employee(4, "D", 5000)); Predicate<Employee> seniorEmp = e -> e.sal > 3000 && e.sal < 6000; OptionalDouble averageSal = list.parallelStream().filter(seniorEmp) .mapToDouble(e -> e.sal).average(); System.out.println(averageSal.getAsDouble()); } }
Employee.java
package com.concretepage.util.stream; public class Employee { public int id; public String name; public int sal; public Employee(int id,String name,int sal ){ this.id = id; this.name = name; this.sal = sal; } }
Sequential Stream
Collection.stream() returns a sequential stream instance for calling collection. To understand Sequential stream, I am calculating the sum of salary for a given predicate. Find the example.SequentialStreamDemo.java
package com.concretepage.util.stream; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class SequentialStreamDemo { public static void main(String[] args) { List<Employee> list = new ArrayList<>(); list.add(new Employee(1, "A", 2000)); list.add(new Employee(2, "B", 3000)); list.add(new Employee(3, "C", 4000)); list.add(new Employee(4, "D", 5000)); Predicate<Employee> juniorEmp = e -> e.sal > 1000 && e.sal < 4000; int salsum = list.stream().filter(juniorEmp) .mapToInt(e -> e.sal).sum(); System.out.println(salsum); } }