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