I have two lists. One list has 6 elements, another one has 3 elements. I need compare both the lists and retain only that information in the aList which matches bList.
public class AClass{
String cname;
int cid;
int aid;
}
public class BClass{
String cname;
int sc_id;
int aid;
}
And the two lists:
List<AClass> aList;
List<BClass> bList;
For example, aList has 1,2,3,4,5,6 and bList has 1,4,5. The comparison has to be done so that aList has 1,4,5 in it.
I've tried the below code. But doesn't work.
aList.retainAll(bList);
Kindly help!
Basically the idea is to compare every element of aList
with every element of bList
while comparing sc_id == e.cid
. You can use streams for that. Looks like this
aList = aList.stream().filter(e -> bList.stream().anyMatch(b -> b.sc_id == e.cid)).collect(Collectors.toList());
Get the ids you want to keep first, then filter against them.
Set<Integer> keepIds = bList.stream().map(BClass:getId).collect(toSet());
List<AClass> filtered = aList.stream
.filter(a -> keepIds.contains(a.getId()))
.collect(toList());
List<Integer> a = List.of(1,2,3,4,5);
List<Integer> b = List.of(1,4,6);
List<Integer> collect = a.stream().filter(b::contains).collect(Collectors.toList());
System.out.println(collect);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.