mercredi 26 décembre 2018

How can I shorten method with if-statments?

I want to shorten this method. Could you tell me how can I make it? I tried somehow, but with bad result. Books list length is not known. It can be 10, but it can be 0 also. I need 3 books if they exist.

public List<Book> findTheLatest3Books() {
    List<Book> books = new ArrayList<>(bookRepository.findAllByOrderByDateOfCreation());
    List<Book> listOf3LatestBooks = new ArrayList<>();
    if (books.size() >= 3) {
        for (int i = 0; i < 3; i++) {
            if (books.get(i).isAvailable()) {
                listOf3LatestBooks.add(books.get(i));
            }
        }
    }
    if (books.size() == 2) {
        for (int i = 0; i < 2; i++) {
            if (books.get(i).isAvailable()) {
                listOf3LatestBooks.add(books.get(i));
            }
        }
    }
    if (books.size() == 1) {
        for (int i = 0; i < 1; i++) {
            if (books.get(i).isAvailable()) {
                listOf3LatestBooks.add(books.get(i));
            }
        }
    }
    if (books.size() == 0) {
        throw new IllegalArgumentException("No books in DB");
    }
    return listOf3LatestBooks;
}

Aucun commentaire:

Enregistrer un commentaire