forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample3.java
More file actions
46 lines (35 loc) · 1.08 KB
/
Copy pathExample3.java
File metadata and controls
46 lines (35 loc) · 1.08 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
package modern.challenge;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class Example3 {
private static final String NOT_FOUND = "NOT FOUND";
public void example3() {
List<Book> books = Arrays.asList();
// Avoid
Optional<Book> book = books.stream()
.filter(b -> b.getPrice() < 50)
.findFirst();
String title1 = null;
if (book.isPresent()) {
title1 = book.get().getTitle().orElse(NOT_FOUND).toUpperCase();
}
// Prefer
String title2 = books.stream()
.filter(b -> b.getPrice() < 50)
.findFirst()
.flatMap(Book::getTitle)
.map(String::toUpperCase)
.orElse(NOT_FOUND);
}
public class Book {
// getTitle() returns a dummy title
public Optional<String> getTitle() {
return Optional.of("title");
}
// getPrice() returns a dummy price
public int getPrice() {
return 10;
}
}
}