Java 8 两个list比较,找出Java 8中两个集合之间的区别?

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, so I can't just test to see whether a book in the first is contained in the second, I have to determine whether any book in the second collection has the same ID as a book in the first.

I have the below code to compare two collections of books and filter the first collection:

List parentBooks = listOfBooks1.stream().filter(book->

!listOfBooks2.contains(book)).collect(Collectors.toList());

The code doesn't work correctly because I am comparing the objects themselves. I need to compare the objects based on the bookId instead of the whole book object. How should I change the code so it can do the comparison based on the bookId (book.getId())?

解决方案

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());

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值