Skip to content

Solution for Optionals 01 #99

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: exercises/optionals/01
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions BookCollection.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;

public record BookCollection(HashMap<Author, List<Book>> collection) {

Expand All @@ -17,18 +18,18 @@ public void addBook(Author author, Book book) {
collection.get(author).add(book);
}

public Book getBookByTitle(String title) {
public Optional<Book> getBookByTitle(String title) {
for (List<Book> books : collection.values()) {
for (Book b : books) {
if (b.title().equals(title)) {
return b;
return Optional.of(b);
}
}
}
return null;
return Optional.empty();
}

public Author getMostDiligentAuthor() {
public Optional<Author> getMostDiligentAuthor() {
Author mostDiligentAuthor = null;
int mostBooks = 0;
for (Entry<Author, List<Book>> entry : collection.entrySet()) {
Expand All @@ -37,6 +38,6 @@ public Author getMostDiligentAuthor() {
mostBooks = entry.getValue().size();
}
}
return mostDiligentAuthor;
return Optional.ofNullable(mostDiligentAuthor);
}
}
11 changes: 9 additions & 2 deletions Exercise.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,14 @@ public static void main(String[] args) {
collection.addBook(new Author("George RR Martin"), new Book("Das Lied von Eis und Feuer 5"));
collection.addBook(new Author("George RR Martin"), new Book("Das Lied von Eis und Feuer 6"));

System.out.println(collection.getBookByTitle("Das Lied von Eis und Feuer 5"));
System.out.println(collection.getMostDiligentAuthor());
collection
.getBookByTitle("Das Lied von Eis und Feuer 5")
.ifPresentOrElse(
System.out::println, () -> System.out.println("Das gesuchte Buch ist nicht vorhanden"));
collection
.getMostDiligentAuthor()
.ifPresentOrElse(
System.out::println,
() -> System.out.println("Es ist kein entsprechender Autor vorhanden"));
}
}