|
| 1 | +package com.learn.streams_terminal; |
| 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.stream.Collectors; |
| 9 | + |
| 10 | +/** |
| 11 | + * <p> |
| 12 | + * groupingBy(): grouping elements according to a |
| 13 | + * classification function, and returning the results in a {@code Map<K, V>} |
| 14 | + * |
| 15 | + * @apiNote There are 3 different versions of groupingBy(). |
| 16 | + * <ul> |
| 17 | + * <li> groupingBy(classifier) : basically what is a classification value that needs to be applied to stream input.</li> |
| 18 | + * <li> groupingBy(classifier, downstream) : downstream is another collector of any type </li> |
| 19 | + * <li> groupingBy(classifier, supplier, downstream) : supplier which is used to override the default map factory</li> |
| 20 | + * </ul> |
| 21 | + * |
| 22 | + * </p> |
| 23 | + * grouping elements according to a |
| 24 | + * classification function, and returning the results in a {@code Map} |
| 25 | + */ |
| 26 | +public class StreamsGroupingByExample { |
| 27 | + |
| 28 | + public static void main(String[] args) { |
| 29 | + |
| 30 | + System.out.println("Student grouped based on Gender : " + groupingByExample1()); |
| 31 | + System.out.println("Student grouped based on PASS/FAIL : " + groupingByExample2()); |
| 32 | + } |
| 33 | + |
| 34 | + /** |
| 35 | + * <p> |
| 36 | + * Group the Student Based on their Gender |
| 37 | + * </p> |
| 38 | + */ |
| 39 | + public static Map<String, List<Student>> groupingByExample1() { |
| 40 | + return StudentDataBase.getAllStudents() |
| 41 | + .stream() |
| 42 | + .collect(Collectors.groupingBy(Student::getGender)); |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + /** |
| 47 | + * <p> |
| 48 | + * grouping Student by using a customized implementation (i.e. based on PASS ond FAIL ) |
| 49 | + * </p> |
| 50 | + * @return |
| 51 | + */ |
| 52 | + public static Map<String, List<Student>> groupingByExample2() { |
| 53 | + return StudentDataBase.getAllStudents() |
| 54 | + .stream() |
| 55 | + .collect(Collectors.groupingBy(student -> student.getGpa() >= 3.8 ? "PASS" : "FAIL")); |
| 56 | + } |
| 57 | +} |
0 commit comments