I have two list ListA listA = new ArrayList() and ListB listB = new ArrayList() both contain object of type Position object and Position contain these variables.
Position {
String account;
String Date;
String Cycle;
String Status;
}
and if for example my lists has values like this
ListA = ["ACC1","20-Jan-23","1","open"],
["ACC1","20-Jan-23","2","closing"],
["ACC2","20-Jan-23","1","open"],
["ACC2","20-Jan-23","2","closing"],
["ACC3","20-Jan-23","1","open"],
["ACC3","20-Jan-23","2","closing"]
ListB = ["ACC1","20-Jan-23","1","open"],
["ACC1","20-Jan-23","2","closing"],
["ACC2","20-Jan-23","1","open"],
["ACC2","20-Jan-23","2","closed"],
["ACC3","20-Jan-23","1","open"]
now my requirement is from the above both lists, I need to find out and extract all accounts that exactly matches in the other list but uniquely, meaning
"ACC1" having two objects in listA and same exists in ListB so this the right candidate that i needed to extract
"ACC2" having two objects in both lists but only one matching exactly same with listB, but other record doesnt match because the status values differs ('closing' and 'closed') so i need to exclude ACC2
"ACC3" having two objects in listA but not in list B, so i need to exclude this ACC3 as well
so ACC1 is what i'm interested in
Is there any way we can achieve this efficiently using java streams or usual standard way
Thanks
Assuming you have all the necessary getters and have overriden the equals and hashCode methods, for example like this:
You could stream over both lists, order them in an identical way and group them by
accountand use the resulting maps to filter accounts having the same list of Position objects. Example code:UPDATE
you can do the field by field comparison manually. I have added an example using BiPredicates. May be there are some eleganter ways to do this with some 3rd party libraries. But without changing the first approach too much the below should give you the same result without the need to override equals and hashCode.