Find the difference between two collections in Java 8?

前端 未结 2 1023
慢半拍i
慢半拍i 2021-02-02 11:34

I am trying to make a List of all of the books in one Collection that are not present in another. My problem is that I need to compare based on book ID

2条回答
  •  臣服心动
    2021-02-02 12:23

    List books1 = ...;
    List books2 = ...;
    Set ids = books2.stream()
            .map(Book::getId)
            .collect(Collectors.toSet());
    List parentBooks = books1.stream()
            .filter(book -> !ids.contains(book.getId()))
            .collect(Collectors.toList());
    

提交回复
热议问题