Skip to content

Commit 0fec070

Browse files
committed
Adding Streams Example
1 parent dc95c40 commit 0fec070

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.learn.streams;
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.function.Predicate;
9+
import java.util.stream.Collectors;
10+
11+
public class StreamsExample {
12+
13+
public static void main(String[] args) {
14+
15+
// we want student name and their activities in a Map
16+
Map<String, List<String>> studentActivitiesMap = StudentDataBase.getAllStudents()
17+
.stream()
18+
.collect(Collectors.toMap(Student::getName, Student::getActivities));
19+
20+
/**
21+
* collect method starts the whole process.
22+
*/
23+
System.out.println(studentActivitiesMap);
24+
25+
// with filter
26+
Map<String, List<String>> studentActivitiesMapWithFilter = StudentDataBase.getAllStudents()
27+
.stream()
28+
.filter(student -> student.getGradeLevel() >= 3)
29+
.collect(Collectors.toMap(Student::getName, Student::getActivities));
30+
System.out.println(studentActivitiesMapWithFilter);
31+
32+
Predicate<Student> predicate1 = student -> student.getGradeLevel() >= 3;
33+
Predicate<Student> predicate2 = student -> student.getGpa() >= 3.9;
34+
Map<String, List<String>> studentActivitiesMapWithTwoFilter = StudentDataBase.getAllStudents()
35+
.stream()
36+
.filter(predicate1)
37+
.filter(predicate2)
38+
.collect(Collectors.toMap(Student::getName, Student::getActivities));
39+
System.out.println(studentActivitiesMapWithTwoFilter);
40+
41+
Predicate<Student> predicate4 = (student -> {
42+
System.out.println(student);
43+
return student.getGradeLevel() >= 3;
44+
});
45+
46+
/**
47+
* collect method starts the whole process.
48+
* if we don't have collect then this won't even start.
49+
* Streams are Lazy.
50+
* i.e. No Intermediate Operations will be invoked until the terminal operation is invoked.
51+
*/
52+
StudentDataBase.getAllStudents()
53+
.stream()
54+
.filter(predicate4);
55+
}
56+
}

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ This repository contains the basic &amp; advance level examples related to Java
2121
* [Refactoring Method Reference](Modern-Java-Examples/src/com/learn/methodreference/RefactorMethodReferenceExample.java)
2222
* [Constructor Reference](Modern-Java-Examples/src/com/learn/constructorreference/ConstructorReferenceExample.java)
2323
* [Lambdas and Local Variables](Modern-Java-Examples/src/com/learn/lambdas/LambdaVariable1.java)
24+
* [Streams](Modern-Java-Examples/src/com/learn/streams)
25+
* [Stream Example](Modern-Java-Examples/src/com/learn/streams/StreamsExample.java)
2426

2527

2628

0 commit comments

Comments
 (0)