|
| 1 | +package com.learn.streams; |
| 2 | + |
| 3 | +import com.learn.data.Student; |
| 4 | +import com.learn.data.StudentDataBase; |
| 5 | + |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.function.Predicate; |
| 9 | +import java.util.stream.Collectors; |
| 10 | + |
| 11 | +public class StreamsExample { |
| 12 | + |
| 13 | + public static void main(String[] args) { |
| 14 | + |
| 15 | + // we want student name and their activities in a Map |
| 16 | + Map<String, List<String>> studentActivitiesMap = StudentDataBase.getAllStudents() |
| 17 | + .stream() |
| 18 | + .collect(Collectors.toMap(Student::getName, Student::getActivities)); |
| 19 | + |
| 20 | + /** |
| 21 | + * collect method starts the whole process. |
| 22 | + */ |
| 23 | + System.out.println(studentActivitiesMap); |
| 24 | + |
| 25 | + // with filter |
| 26 | + Map<String, List<String>> studentActivitiesMapWithFilter = StudentDataBase.getAllStudents() |
| 27 | + .stream() |
| 28 | + .filter(student -> student.getGradeLevel() >= 3) |
| 29 | + .collect(Collectors.toMap(Student::getName, Student::getActivities)); |
| 30 | + System.out.println(studentActivitiesMapWithFilter); |
| 31 | + |
| 32 | + Predicate<Student> predicate1 = student -> student.getGradeLevel() >= 3; |
| 33 | + Predicate<Student> predicate2 = student -> student.getGpa() >= 3.9; |
| 34 | + Map<String, List<String>> studentActivitiesMapWithTwoFilter = StudentDataBase.getAllStudents() |
| 35 | + .stream() |
| 36 | + .filter(predicate1) |
| 37 | + .filter(predicate2) |
| 38 | + .collect(Collectors.toMap(Student::getName, Student::getActivities)); |
| 39 | + System.out.println(studentActivitiesMapWithTwoFilter); |
| 40 | + |
| 41 | + Predicate<Student> predicate4 = (student -> { |
| 42 | + System.out.println(student); |
| 43 | + return student.getGradeLevel() >= 3; |
| 44 | + }); |
| 45 | + |
| 46 | + /** |
| 47 | + * collect method starts the whole process. |
| 48 | + * if we don't have collect then this won't even start. |
| 49 | + * Streams are Lazy. |
| 50 | + * i.e. No Intermediate Operations will be invoked until the terminal operation is invoked. |
| 51 | + */ |
| 52 | + StudentDataBase.getAllStudents() |
| 53 | + .stream() |
| 54 | + .filter(predicate4); |
| 55 | + } |
| 56 | +} |
0 commit comments