Repository navigation
Expand file tree
/
Copy pathMain.java
More file actions
78 lines (58 loc) · 2.06 KB
/
Copy pathMain.java
File metadata and controls
78 lines (58 loc) · 2.06 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
74
75
76
77
78
package modern.challenge;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
public class Main {
private static final String NOT_FOUND = "NOT FOUND";
private static final List<Book> BOOKS
= List.of(new Book(15, "Book1"), new Book(25, "Book2"));
private static final Optional<Author> AUTHOR
= Optional.of(new Author("Author", BOOKS));
public static void main(String[] args) {
System.out.println(findFirstCheaperBookAvoid(20));
System.out.println(findFirstCheaperBookAlsoAvoid(20));
System.out.println(findFirstCheaperBookPrefer(20));
System.out.println();
validateAuthorOfBookAvoid(new Book(15, "Book1"));
validateAuthorOfBookPrefer(new Book(15, "Book1"));
}
// Avoid
public static String findFirstCheaperBookAvoid(int price) {
Optional<Book> book = BOOKS.stream()
.filter(b -> b.getPrice() < price)
.findFirst();
if (book.isPresent()) {
return book.get().getName();
} else {
return NOT_FOUND;
}
}
// Avoid
public static String findFirstCheaperBookAlsoAvoid(int price) {
Optional<Book> book = BOOKS.stream()
.filter(b -> b.getPrice() < price)
.findFirst();
return book.map(Book::getName)
.orElse(NOT_FOUND);
}
// Prefer
public static String findFirstCheaperBookPrefer(int price) {
return BOOKS.stream()
.filter(b -> b.getPrice() < price)
.findFirst()
.map(Book::getName)
.orElse(NOT_FOUND);
}
// Avoid
public static void validateAuthorOfBookAvoid(Book book) {
if (!AUTHOR.isPresent()
|| !AUTHOR.get().getBooks().contains(book)) {
throw new NoSuchElementException();
}
}
// Prefer
public static void validateAuthorOfBookPrefer(Book book) {
AUTHOR.filter(a -> a.getBooks().contains(book))
.orElseThrow();
}
}