Search code examples
javaarrayssearcharraylistbluej

ArrayList Book Search


I've to create a library system in bluej and it has to be able to search for a book. However, I have a problem. When I try and search for a book the result is always no books available... How do I sort this so the result shows the book is available?

private List<Book> collection;

public Library()
{
    collection = new ArrayList<Book>();
}

public void addBook(Book book)
{
    collection.add(book);
}

public String titleSearch()
{
    String titleSearch = "\n ";
    for(int i = 0; i < collection.size(); i++){
        if(titleSearch.equalsIgnoreCase(collection.get(i).getTitle())){

            titleSearch = ("\n Book Avaliable");

        }else{
            titleSearch = ("\n No Books Avaliable ");
        }
    }
    return titleSearch;
}

Solution

  • if you are using Java 8 you can use stream

    public String searchTitle(String titleSearch) {
    
        if(collection.stream().anyMatch(book->{return titleSearch.equalsIgnoreCase(book.getTitle());})){
            return "\n Book Avaliable";
        }
        else{
            return "\n No Books Avaliable";
        }
    }
    

    you can also use parallelStream() instead of stream()