I have a list of books. Some of these books are the same however they are not duplicates as they differ because of a variable called copyNumber. Example. Book1(Title: Spiderman, ISBN: 1111, CopyNo: 1)
, Book2(Title: Spiderman, ISBN: 1111, CopyNo: 2)
, Book3(Title: Spiderman, ISBN: 1111, CopyNo: 3)
, Book4(Title: Alice in wonderland, ISBN: 2222, CopyNo: 1)
, Book5(Title: Alice in wonderland, ISBN: 2222, CopyNo: 2)
. So my goal is to list all these books in order of their copy numbers, find the book (and its copies) via its ISBN number, then delete the last copy. So if i was to call deleteBook("1111");
for the example above i would delete the 3rd copy of spiderman. If i was to call deleteBook("2222");
I would delete the second copy of Alice in wonderland
public void deleteBook(String isbn){
Collections.sort(books, new OrderBooksByCopyNumber());
Book book = books.stream().filter((b) -> (b.getISBNNumber().equals(isbn))).findFirst().get();
books.remove(book);
}
The code above is close to what i want how ever i don't want findFirst()
, I want to do the equivalent of findLast()
. Below is my comparator if it's of any relevance. Thanks to anyone who can help!
private class OrderBooksByCopyNumber implements Comparator<Book>{
@Override
public int compare(Book o1, Book o2) {
return o1.getCopyNumber() < o2.getCopyNumber() ? -1 : o1.getCopyNumber() == o2.getCopyNumber() ? 0 : 1;
}
}