简体   繁体   English

仅当 ArrayList B 中对象的组件不存在时才添加到 ArrayList A

[英]Adding to ArrayList A only if a component of a object in ArrayList B Doesn't exist

I have two objects: Books and BookLoans.我有两个对象:Books 和 BookLoans。 All the books are stored on a ArrayList called books and Bookloans on loans.所有的书都存储在一个 ArrayList 中,称为书籍和借书书。

A component of BookLoans is bookId. BookLoans 的一个组件是 bookId。 I want all books to be added to a combobox if the bookId doesn't already exist on the BookLoans List.如果 BookLoans 列表中不存在 bookId,我希望将所有书籍添加到组合框。 Both the lists are different sizes.这两个列表的大小不同。

I'm using MVC and the View side of the combobox is working.我正在使用 MVC,并且组合框的视图端正在工作。

I presume it will consists of two for-loops so this is my current attempt:我认为它将由两个 for 循环组成,所以这是我目前的尝试:

 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.目前,当两个数组列表中都有对象时,我得到的唯一结果是组合框中没有任何内容。

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.正如 JB Nizet 指出的那样,您应该将检查哪些书籍借出的部分分离到一个单独的方法中,以使您的代码更简单、更清晰(然后您可以编写类似books.stream().filter(book -> !hasBeenLoaned(book)).map(book -> book.getTitle()) 。为了简洁起见,我选择不这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM