|
| 1 | +package com.javatechie.parralel_stream; |
| 2 | + |
| 3 | +import com.javatechie.map_reduce.Employee; |
| 4 | +import com.javatechie.map_reduce.EmployeeDatabase; |
| 5 | + |
| 6 | +import java.util.List; |
| 7 | +import java.util.stream.IntStream; |
| 8 | + |
| 9 | +public class ParallelStreamExample { |
| 10 | + |
| 11 | + |
| 12 | + public static void main(String[] args) { |
| 13 | + long start=0; |
| 14 | + long end=0; |
| 15 | + |
| 16 | + start=System.currentTimeMillis(); |
| 17 | + IntStream.range(1,100).forEach(System.out::println); |
| 18 | + end=System.currentTimeMillis(); |
| 19 | + System.out.println("Plain stream took time : "+(end-start)); |
| 20 | + |
| 21 | + System.out.println("============================================"); |
| 22 | + |
| 23 | + start=System.currentTimeMillis(); |
| 24 | + IntStream.range(1,100).parallel().forEach(System.out::println); |
| 25 | + end=System.currentTimeMillis(); |
| 26 | + System.out.println("Parallel stream took time : "+(end-start)); |
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | + IntStream.range(1,10).forEach(x->{ |
| 31 | + System.out.println("Thread : "+Thread.currentThread().getName()+" : "+x); |
| 32 | + }); |
| 33 | + |
| 34 | + IntStream.range(1,10).parallel().forEach(x->{ |
| 35 | + System.out.println("Thread : "+Thread.currentThread().getName()+" : "+x); |
| 36 | + }); |
| 37 | + |
| 38 | + List<Employee> employees = EmployeeDatabase.getEmployees(); |
| 39 | + |
| 40 | + //normal |
| 41 | + start=System.currentTimeMillis(); |
| 42 | + double salaryWithStream = employees.stream() |
| 43 | + .map(Employee::getSalary).mapToDouble(i -> i).average().getAsDouble(); |
| 44 | + end=System.currentTimeMillis(); |
| 45 | + |
| 46 | + System.out.println("Normal stream execution time : "+(end-start)+" : Avg salary : "+salaryWithStream); |
| 47 | + |
| 48 | + start=System.currentTimeMillis(); |
| 49 | + double salaryWithParallelStream = employees.parallelStream() |
| 50 | + .map(Employee::getSalary).mapToDouble(i -> i).average().getAsDouble(); |
| 51 | + |
| 52 | + end=System.currentTimeMillis(); |
| 53 | + |
| 54 | + System.out.println("Parallel stream execution time : "+(end-start)+" : Avg salary : "+salaryWithParallelStream); |
| 55 | + } |
| 56 | +} |
0 commit comments