java list查找元素是否存在,使用Java 8在列表中查找其他列表中不存在的元素

I have 2 lists. The requirement is to filter out elements in list1 that are not in list2 based on condition.

Class Fighter

{

String name;

String address;

}

List pairs1 = new ArrayList();

pairs1.add(new Fighter("a", "a"));

pairs1.add(new Fighter("b", "a"));

List pairs2 = new ArrayList();

pairs2.add(new Fighter("a", "c"));

pairs2.add(new Fighter("a", "d"));

Set finalValues = new HashSet<>();

finalValues = pairs1.stream().filter(firstList ->

pairs2.stream().noneMatch(secondList ->

firstList.getName().equals(secondList.getName())

&& firstList.getName().equals(secondList.getName()))).collect(Collectors.toSet());

System.out.println(finalValues);

Expected Output : a=a, b=a

Explanation: Elements in list1 that are not in list2

The above code is not giving the expected output. Please let me know how the above stream code can be corrected to get the output

解决方案

First override the equals and hashcode methods in Fighter class.

@Override

public boolean equals(Object o) {

if (o == this)

return true;

if (!(o instanceof Fighter))

return false;

Fighter f = (Fighter) o;

return f.name.equals(name) && f.address.equals(address);

}

@Override

public int hashCode() {

int result = name.hashCode();

result = 31 * result + address.hashCode();

return result;

}

Then create a Set from pairs2. Finally use it's contains method to get the set difference. Here's how it looks,

Set pairs2Set = new HashSet<>(pairs2);

Set setDiff = pairs1.stream()

.filter(f -> !pairs2Set.contains(f))

.collect(Collectors.toSet());

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值