|
| 1 | +package com.learn.parallelstream; |
| 2 | + |
| 3 | +import com.learn.data.Student; |
| 4 | +import com.learn.data.StudentDataBase; |
| 5 | + |
| 6 | +import java.util.List; |
| 7 | +import java.util.stream.Collectors; |
| 8 | + |
| 9 | +public class ParallelStreamExample1 { |
| 10 | + |
| 11 | + public static void main(String[] args) { |
| 12 | + sequentialStudentActivities(); |
| 13 | + parallelStudentActivities(); |
| 14 | + } |
| 15 | + |
| 16 | + public static List<String> sequentialStudentActivities() { |
| 17 | + long startTime = System.currentTimeMillis(); |
| 18 | + List<String> studentActivities = StudentDataBase.getAllStudents() |
| 19 | + .stream() //Stream<Student> |
| 20 | + .map(Student::getActivities) // Stream<List<String>> -- stateless |
| 21 | + .flatMap(List::stream) // Stream<String> -- stateless |
| 22 | + .distinct() // stateful |
| 23 | + .sorted() //stateful |
| 24 | + .collect(Collectors.toList()); |
| 25 | + long endTime = System.currentTimeMillis(); |
| 26 | + System.out.println("Sequential Time Take = " + (endTime - startTime)); |
| 27 | + return studentActivities; |
| 28 | + } |
| 29 | + |
| 30 | + public static List<String> parallelStudentActivities() { |
| 31 | + long startTime = System.currentTimeMillis(); |
| 32 | + List<String> studentActivities = StudentDataBase.getAllStudents() |
| 33 | + .stream() |
| 34 | + .parallel() |
| 35 | + .map(Student::getActivities) |
| 36 | + .flatMap(List::stream) |
| 37 | + .distinct() |
| 38 | + .sorted() |
| 39 | + .collect(Collectors.toList()); |
| 40 | + long endTime = System.currentTimeMillis(); |
| 41 | + System.out.println("Parallel Time Take = " + (endTime - startTime)); |
| 42 | + return studentActivities; |
| 43 | + } |
| 44 | +} |
0 commit comments