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