-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamFlatMap.java
More file actions
73 lines (52 loc) · 1.71 KB
/
Copy pathStreamFlatMap.java
File metadata and controls
73 lines (52 loc) · 1.71 KB
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 lambda_expression.unit12;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
import data.Student;
import data.StudentDataBase;
public class StreamFlatMap {
public static List<String> printStudentActivites() {
List<List<String>> studentActivities = StudentDataBase.getAllStudents().stream() // Stream<Student>
.map(Student::getActivities) // Stream<List<String>>
.collect(toList());
System.out.println(studentActivities);
//its not clean code
Function<List<String>, Stream<String>> activitiesFun = f -> {
f.forEach(s -> {
if (s.equals("swimming")) {
s = s.toUpperCase();
System.out.println(s);
}
});
for (String s : f) {
if (s.equals("swimming")) {
s=null;
}
}
// we can do it in this Case
for(int i=0; i<f.size();i++) {
String string = f.get(i);
if (string.equals("swimming")) {
f.set(i, string.toUpperCase());
}
}
return f.stream();
};
List<String> studentActivitiesFlaten = StudentDataBase.getAllStudents().stream() // Stream<Student>
.map(Student::getActivities) // Stream<List<String>>
.flatMap(activitiesFun) // Stream<String>
.collect(toList());
System.out.println(studentActivitiesFlaten);
List<String> studentActivitiesFlaten2 = StudentDataBase.getAllStudents().stream() // Stream<Student>
.map(Student::getActivities) // Stream<List<String>>
.flatMap(List::stream) // Stream<String>
.collect(toList());
System.out.println(studentActivitiesFlaten2);
System.out.println(studentActivitiesFlaten2);
return null;
}
public static void main(String[] args) {
printStudentActivites();
}
}