如何使用Java流比较两个ArrayList并使用过滤器获取list1 [英] How to compare two ArrayList and get list1 with filter using java streams

查看:342
本文介绍了如何使用Java流比较两个ArrayList并使用过滤器获取list1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表list1&列表类型的list2

I have two lists list1 & list2 of type List

Term{
long sId;
int rowNum;
long psid;
String name;
}

List<Term> list1 = new ArrayList<>();
List<Term> list2 = new ArrayList<>();

我想从list1返回所有项目,其中(list1.psid!= list2.psid).

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

我尝试了这个,但是没有用

I tried this but its not working

public List<Term> getFilteredRowNum(List<Term> list1, List<Term> list2) {
        List<Long> 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());

    }

我想获取满足休憩条件的list1中的所有记录 if(list1.psid!= list2.psid)

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

推荐答案

您正在过滤谓词中查找内部anyMatch为:

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

public List<Term> getFilteredRowNum(List<Term> termList1, List<Term> termList2) {
    return termList1.stream()
            .filter(term1 -> termList2.stream()
                    .anyMatch(term2 -> term1.getSId() == term2.getSId()
                            && term1.getPsid() != term2.getPsid()))
            .collect(Collectors.toList());
}

另一种解决方法是使用groupingBymapping

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<Long, Set<Long>> sIdToPsIdsMap = termList2.stream()
        .collect(Collectors.groupingBy(Term::getSId, 
                Collectors.mapping(Term::getPsid, Collectors.toSet())));

并进一步将其用于filter条件

return termList1.stream()
        .filter(term1 -> sIdToPsIdsMap.containsKey(term1.getSId())
                && !sIdToPsIdsMap.get(term1.getSId()).contains(term1.getPsid()))
        .collect(Collectors.toList());

这篇关于如何使用Java流比较两个ArrayList并使用过滤器获取list1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆