java list term,如何使用Java流比较两个ArrayList并使用过滤器获取list1

I have two lists list1 & list2 of type List

Term{

long sId;

int rowNum;

long psid;

String name;

}

List list1 = new ArrayList<>();

List list2 = new ArrayList<>();

I want to return all the items from list1 where (list1.psid != list2.psid).

I tried this but its not working

public List getFilteredRowNum(List list1, List list2) {

List psid = list2.stream().map(x -> x.getPsid()).collect(Collectors.toList());

return list1.stream().filter(x -> !psid.contains(x.getPsid())).map(x -> x.getRowNum()+1).collect(Collectors.toList());

}

I want to get all the records in list1 which satisfies fallowing condition

if(list1.psid != list2.psid)

Sample Date:

List1: rowNum psId name sid

1 1288 home 101

1 9012 home 101

2 1296 office 150

3 1290 park 161

List2: rowNum psId name sid

1 9012 home 101

2 1296 office 150

3 1290 park 161

List1 psId not in list2 so I am expecting fallowing list as result from list1

Expected: List1

rowNum psId name sid

1 1288 home 101

解决方案

You are looking for an inner anyMatch in the filter predicate as:

public List getFilteredRowNum(List termList1, List termList2) {

return termList1.stream()

.filter(term1 -> termList2.stream()

.anyMatch(term2 -> term1.getSId() == term2.getSId()

&& term1.getPsid() != term2.getPsid()))

.collect(Collectors.toList());

}

Another way to solve that would be to create a Map of sid to a Set of psids present in any of the list using groupingBy and mapping

Map> sIdToPsIdsMap = termList2.stream()

.collect(Collectors.groupingBy(Term::getSId,

Collectors.mapping(Term::getPsid, Collectors.toSet())));

and further using it for filter conditions as

return termList1.stream()

.filter(term1 -> sIdToPsIdsMap.containsKey(term1.getSId())

&& !sIdToPsIdsMap.get(term1.getSId()).contains(term1.getPsid()))

.collect(Collectors.toList());

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值