File tree Expand file tree Collapse file tree 2 files changed +12
-7
lines changed Expand file tree Collapse file tree 2 files changed +12
-7
lines changed Original file line number Diff line number Diff line change 1
1
import java .util .ArrayList ;
2
2
import java .util .HashMap ;
3
3
import java .util .List ;
4
+ import java .util .Optional ;
4
5
import java .util .Map .Entry ;
5
6
6
7
public record BookCollection (HashMap <Author , List <Book >> collection ) {
@@ -17,18 +18,18 @@ public void addBook(Author author, Book book) {
17
18
collection .get (author ).add (book );
18
19
}
19
20
20
- public Book getBookByTitle (String title ) {
21
+ public Optional < Book > getBookByTitle (String title ) {
21
22
for (List <Book > books : collection .values ()) {
22
23
for (Book b : books ) {
23
24
if (b .title ().equals (title )) {
24
- return b ;
25
+ return Optional . of ( b ) ;
25
26
}
26
27
}
27
28
}
28
- return null ;
29
+ return Optional . empty () ;
29
30
}
30
31
31
- public Author getMostDiligentAuthor () {
32
+ public Optional < Author > getMostDiligentAuthor () {
32
33
Author mostDiligentAuthor = null ;
33
34
int mostBooks = 0 ;
34
35
for (Entry <Author , List <Book >> entry : collection .entrySet ()) {
@@ -37,6 +38,6 @@ public Author getMostDiligentAuthor() {
37
38
mostBooks = entry .getValue ().size ();
38
39
}
39
40
}
40
- return mostDiligentAuthor ;
41
+ return Optional . ofNullable ( mostDiligentAuthor ) ;
41
42
}
42
43
}
Original file line number Diff line number Diff line change @@ -21,7 +21,11 @@ public static void main(String[] args) {
21
21
collection .addBook (new Author ("George RR Martin" ), new Book ("Das Lied von Eis und Feuer 5" ));
22
22
collection .addBook (new Author ("George RR Martin" ), new Book ("Das Lied von Eis und Feuer 6" ));
23
23
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" ));
26
30
}
27
31
}
You can’t perform that action at this time.
0 commit comments