I have 2 custom list of Java objects.
@Data
Class A{
int no;
int age;
int foo;
int bar;
}
List<A> aList = populateFromDB();
List<A> bList = populateFromReq();
Now I want a 3rd list which will contain filtered objects from bList.
The filtering is based on this criteria :
no should match;
age OR foo anyone should differ;
Sample Data set :
Input :
aList = [{2,20,50,60} , {3,25,40,60} , {4,40,10,20}]
bList = [{2,10,50,60} , {3,25,50,60} , {4,40,10,20}]
Output :
filteredList = [{2,10,50,60} , {3,25,50,60}]
// first 2 elements in bList are different hence they should be added to the filtered list.
// aList contains records from DB.
// bList contains records of same size as aList but few elements are different.
// Need to compare bList with aList and find the records that are different and create a separate list and update those records in DB.
I am trying this code :
List<A> filteredList = bList.stream()
.filter(i -> aList.stream()
.anyMatch(j -> (j.getNo() == i.getNo() &&
(j.getAge() != i.getAge() ||
j.getFoo() != i.getFoo())
)
)
)
.collect(Collectors.toList());
But the above is not giving me desired results. It is giving me records which does not fulfil the criteria I have mentioned. I am not sure where I am making wrong.
I have also tried the below code :
List<A> intersect = a.stream()
.filter(b::contains)
.collect(Collectors.toList());
Can anyone help me how to compare 2 custom list based on some fields and form a new list.
UPDATE-1 : Its not about comparing String. So for simplicity sake I am replacing strings with Integers.
UPDATE-2 : Added sample i/p and o/p data.