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

Sruthi :

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
Naman :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=126022&siteId=1