java list intersect,Java 8中两个列表对象的交集

An intersection of Two Lists Objects in java 8. Can some tell me what am I doing wrong?

List originalStudent = new ArrayList<>();

List newStudent = new ArrayList<>();

List intersectListStudent = new LinkedList<>()

originalStudent.add(new Student("William", "Tyndale",1));

originalStudent.add(new Student("Jonathan", "Edwards",2));

originalStudent.add(new Student("Martin", "Luther"),3);

newStudent.add(new Student("Jonathan", "Edwards",2));

newStudent.add(new Student("James", "Tyndale",4));

newStudent.add(new Student("Roger", "Moore",5));

originalStudent.forEach(n ->

newStudent.stream()

.filter(db -> !n.getName().equals(db.getName()) &&

!n.getLastName().equals(db.getLastName()))

.forEach(student-> intersectListStudent .add(student)));

解决方案

Can some tell me what am I doing wrong?

You violate the Side-effects principle of java-stream which in a nutshell says that a stream shouldn't modify another collection while performing the actions through the pipelines. I haven't tested your code, however, this is not a way you should treat streams.

How to do it better?

Simply use the List::contains in the filter's predicate to get rid of the unique values.

List students = originalStudent.stream()

.filter(newStudent::contains)

.collect(Collectors.toList());

This solution (understand the method List::contains) is based on the implemented equality comparison using Object::equals. Hence, there is needed to override the very same method in the class Student.

Edit: Please, be aware that that automatically overriding the Object::equals will mind the id to the equality computation. Therefore the equality will be based on the name and surname only. (thanks to @nullpointer).

Without the Object::equals overridden?

You have to perform the comparison in the filter using another stream and the method Stream::anyMatch which returns true if the predicate is qualified.

List students = originalStudent.stream()

.filter(os -> newStudent.stream() // filter

.anyMatch(ns -> // compare both

os.getName().equals(ns.getName() && // name

os.getLastName().equals(ns.getLastName()))) // last name

.collect(Collectors.toList());

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值