-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamsFindExample.java
More file actions
51 lines (41 loc) · 1.51 KB
/
StreamsFindExample.java
File metadata and controls
51 lines (41 loc) · 1.51 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
package com.learn.streams;
import com.learn.data.Student;
import com.learn.data.StudentDataBase;
import java.util.Optional;
public class StreamsFindExample {
public static void main(String[] args) {
Optional<Student> studentOptionalFindAny = findAnyStudent();
if (studentOptionalFindAny.isPresent()) {
System.out.println(studentOptionalFindAny.get());
}
Optional<Student> studentOptionalFindFirst = findFirstStudent();
if (studentOptionalFindFirst.isPresent()) {
System.out.println(studentOptionalFindFirst.get());
}
}
/**
* <p>
* findFirst() : Returns the first element it finds ar per condition in the stream.
* </p>
* @return
*/
public static Optional<Student> findFirstStudent() {
return StudentDataBase.getAllStudents().stream()
.filter(student -> student.getGpa() >= 3.9)
.findFirst();
}
/**
* <p>
* findAny() : Returns the first encountered element int the stream.
* </p>
* @return
*/
public static Optional<Student> findAnyStudent() {
return StudentDataBase.getAllStudents().stream()
// it checked for Adam, Jenny, and Emily
.filter(student -> student.getGpa() >= 3.9)
// as soon it found a student with this filter criteria, it returned that student
// and it did not not execute any one of the other student below this.
.findAny();
}
}