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