-1

I have two objects: Books and BookLoans. All the books are stored on a ArrayList called books and Bookloans on loans.

A component of BookLoans is bookId. I want all books to be added to a combobox if the bookId doesn't already exist on the BookLoans List. Both the lists are different sizes.

I'm using MVC and the View side of the combobox is working.

I presume it will consists of two for-loops so this is my current attempt:

 int length = books.size();
 int loansLength = loans.size();
 String[] listBooksCombo = new String[length];
 for (int i = 0; i < loansLength; i++){

            for(int j = 0; j < length; j++){
                title = books.get(j).getTitle(); // Currently for testing purposes the getTitle and getBookId both are titles of a book
                if(loans.get(i).getBookId() != title ){
                    listBooksCombo[j] = title;  


                }
                currentView.comboBox(listBooksCombo); // sets the combo model
            }

   }

Currently the only result i've had is nothing appear in the combo box when there are objects in both array lists.

Ross
  • 141
  • 7
  • https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – PM 77-1 Aug 12 '19 at 16:42
  • You need to divide the work into smaller pieces, to avoid such logic mistakes. The logic should be `for (each book in books) { if (existsInBookLoans(book) { addBookToCombo(book) } `. Now you have a simpler algorighm to implement inside the method `existsInBookLoans`. You can't know the length of the combo in advance, so use a List, not a array. – JB Nizet Aug 12 '19 at 16:43

1 Answers1

0

Here's how I would do it. The explanation is in the comments.

// collect the IDs of the book loans in a set - this makes lookup faster 
Set<String> loanedBookIds = HashSet<>();
for (BookLoan loan : bookLoans) {
    loanedBookIds.add(loan.getBookId());
}

// put the names of unloaned books here
List<String> unloanedTitles = new ArrayList<>();
for (Book book : books) {
    // add all books whose IDs are not in `loanedBookIds`
    if (!loanedBookIds.contains(book.getId())) {
        unloanedTitles.add(book.getTitle());
    }
}

// show titles in the ComboBox
currentView.comboBox(unloanedTitles);

As JB Nizet pointed out, you should separate the part that checks for which books are loaned into a separate method to make your code simpler and cleaner (then you can just write something like books.stream().filter(book -> !hasBeenLoaned(book)).map(book -> book.getTitle()). I've chosen not to do that here merely for brevity.

Leo Aso
  • 11,898
  • 3
  • 25
  • 46