|
| 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.Set; |
| 9 | +import java.util.stream.Collectors; |
| 10 | + |
| 11 | +/** |
| 12 | + * <p> |
| 13 | + * <code>mapping()</code> Collector applies a transformation function first and then |
| 14 | + * collects the data in a collection ( could be any type of collection ) |
| 15 | + * it takes 2 input : |
| 16 | + * First is the Function, which is a mapper and second is a downstream which represents |
| 17 | + * a type of collection which we want the result to be collected. |
| 18 | + * |
| 19 | + * </p> |
| 20 | + */ |
| 21 | +public class StreamsMappingExample { |
| 22 | + |
| 23 | + public static void main(String[] args) { |
| 24 | + |
| 25 | + System.out.println("Student Name List : " + mapping1()); |
| 26 | + |
| 27 | + System.out.println("Student Name Set : " + mapping2()); |
| 28 | + |
| 29 | + System.out.println("Student Names for each Grade : " + gradeToStudentName()); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * this is going to collect List of Students Name i.e type String |
| 34 | + * @return |
| 35 | + */ |
| 36 | + public static List<String> mapping1() { |
| 37 | + return StudentDataBase.getAllStudents().stream() |
| 38 | + .collect(Collectors.mapping(Student::getName, Collectors.toList())); |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * this is going to collect Set of Students Name i.e type String |
| 43 | + * @return |
| 44 | + */ |
| 45 | + public static Set<String> mapping2() { |
| 46 | + return StudentDataBase.getAllStudents().stream() |
| 47 | + .collect(Collectors.mapping(Student::getName, Collectors.toSet())); |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * @apiNote |
| 52 | + * The {@code mapping()} collectors are most useful when used in a |
| 53 | + * multi-level reduction, such as downstream of a {@code groupingBy} or |
| 54 | + * {@code partitioningBy}. For example, given a stream of |
| 55 | + * {@code Person}, to accumulate the set of last names in each city: |
| 56 | + * <pre>{@code |
| 57 | + * Map<City, Set<String>> lastNamesByCity |
| 58 | + * = people.stream().collect( |
| 59 | + * groupingBy(Person::getCity, |
| 60 | + * mapping(Person::getLastName, |
| 61 | + * toSet()))); |
| 62 | + * }</pre> |
| 63 | + */ |
| 64 | + public static Map<Integer, List<String>> gradeToStudentName() { |
| 65 | + return StudentDataBase.getAllStudents().stream() |
| 66 | + .collect( |
| 67 | + Collectors.groupingBy(Student::getGradeLevel, |
| 68 | + Collectors.mapping(Student::getName, Collectors.toList()) |
| 69 | + ) |
| 70 | + ); |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments