|
| 1 | +package com.learn.streams_terminal; |
| 2 | + |
| 3 | +import com.learn.data.Student; |
| 4 | +import com.learn.data.StudentDataBase; |
| 5 | + |
| 6 | +import java.util.Comparator; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.Optional; |
| 9 | + |
| 10 | +import static java.util.stream.Collectors.*; |
| 11 | + |
| 12 | +public class StreamsMinMaxCollectingThenExample { |
| 13 | + |
| 14 | + public static void main(String[] args) { |
| 15 | + |
| 16 | + System.out.println("Max Student with Optional" + optionalStudentWithMaximumGpa()); |
| 17 | + System.out.println("Max Student without Optional" + studentWithMaximumGpa()); |
| 18 | + |
| 19 | + System.out.println("Student with Least GPA in each Grade : " + studentWithMinimumGpa()); |
| 20 | + |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * <p> |
| 25 | + * Calculate top Gpa Student in each Grade. |
| 26 | + * Here value is wrapped inside the Optional, |
| 27 | + * but we can avoid this by using CollectingAndThen |
| 28 | + * </p> |
| 29 | + */ |
| 30 | + public static Map<Integer, Optional<Student>> optionalStudentWithMaximumGpa() { |
| 31 | + return StudentDataBase.getAllStudents() |
| 32 | + .stream() |
| 33 | + .collect(groupingBy(Student::getGradeLevel, |
| 34 | + maxBy(Comparator.comparing(Student::getGpa)))); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * <p> |
| 39 | + * collectingAndThen() : is going to get the Student if available and then assign that as an value. |
| 40 | + * </p> |
| 41 | + * @return |
| 42 | + */ |
| 43 | + public static Map<Integer, Student> studentWithMaximumGpa() { |
| 44 | + return StudentDataBase.getAllStudents() |
| 45 | + .stream() |
| 46 | + .collect(groupingBy(Student::getGradeLevel, |
| 47 | + collectingAndThen(maxBy(Comparator.comparing(Student::getGpa)), |
| 48 | + Optional::get) |
| 49 | + ) |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + /** |
| 55 | + * <p> |
| 56 | + * Calculate Least Gpa Student in each Grade. |
| 57 | + * </p> |
| 58 | + * @return |
| 59 | + */ |
| 60 | + public static Map<Integer, Student> studentWithMinimumGpa() { |
| 61 | + return StudentDataBase.getAllStudents() |
| 62 | + .stream() |
| 63 | + .collect( |
| 64 | + groupingBy(Student::getGradeLevel, |
| 65 | + collectingAndThen( |
| 66 | + minBy(Comparator.comparing(Student::getGpa)), |
| 67 | + Optional::get) |
| 68 | + ) |
| 69 | + ); |
| 70 | + } |
| 71 | +} |
0 commit comments