Skip to content

Commit 5d0cc83

Browse files
committed
Solution Optionals 02
1 parent ab560a7 commit 5d0cc83

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

BookCollection.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import java.util.ArrayList;
22
import java.util.HashMap;
33
import java.util.List;
4+
import java.util.Optional;
45
import java.util.Map.Entry;
56

67
public record BookCollection(HashMap<Author, List<Book>> collection) {
@@ -17,18 +18,18 @@ public void addBook(Author author, Book book) {
1718
collection.get(author).add(book);
1819
}
1920

20-
public Book getBookByTitle(String title) {
21+
public Optional<Book> getBookByTitle(String title) {
2122
for (List<Book> books : collection.values()) {
2223
for (Book b : books) {
2324
if (b.title().equals(title)) {
24-
return b;
25+
return Optional.of(b);
2526
}
2627
}
2728
}
28-
return null;
29+
return Optional.empty();
2930
}
3031

31-
public Author getMostDiligentAuthor() {
32+
public Optional<Author> getMostDiligentAuthor() {
3233
Author mostDiligentAuthor = null;
3334
int mostBooks = 0;
3435
for (Entry<Author, List<Book>> entry : collection.entrySet()) {
@@ -37,6 +38,6 @@ public Author getMostDiligentAuthor() {
3738
mostBooks = entry.getValue().size();
3839
}
3940
}
40-
return mostDiligentAuthor;
41+
return Optional.ofNullable(mostDiligentAuthor);
4142
}
4243
}

Exercise.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,11 @@ public static void main(String[] args) {
2121
collection.addBook(new Author("George RR Martin"), new Book("Das Lied von Eis und Feuer 5"));
2222
collection.addBook(new Author("George RR Martin"), new Book("Das Lied von Eis und Feuer 6"));
2323

24-
System.out.println(collection.getBookByTitle("Das Lied von Eis und Feuer 5"));
25-
System.out.println(collection.getMostDiligentAuthor());
24+
collection.getBookByTitle("Das Lied von Eis und Feuer 5")
25+
.ifPresentOrElse(System.out::println,
26+
() -> System.out.println("Das gesuchte Buch ist nicht vorhanden"));
27+
collection.getMostDiligentAuthor()
28+
.ifPresentOrElse(System.out::println,
29+
() -> System.out.println("Es ist kein entsprechender Autor vorhanden"));
2630
}
2731
}

0 commit comments

Comments
 (0)