How to compare two ArrayList and get list1 with filter using java streams

百般思念 提交于 2021-02-04 19:36:07

问题


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

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

    }

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

回答1:


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

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

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


来源:https://stackoverflow.com/questions/57194591/how-to-compare-two-arraylist-and-get-list1-with-filter-using-java-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!