I have two lists –
ArrayList<MyObject> list1 -> [obj1, obj2, obj3, obj4, obj5, obj6]
ArrayList<MyObject> list2 -> [obj1, obj6, obj7, obj8]
Is there any utility method already existing in java api which can give a list of only common records of two?
expected list ->
[obj1, obj6]
MyObject looks like this –
class MyObject {
public Integer number;
public String name;
public Integer parent;
public String parentName;
}
I only need to use number and name to do the comparison.
i am aware of approach using retainAll or removeAll to get the desired list. The problem however is, I cannot override equals method of MyObject as it is used for some different purpose. And the retainAll or removeAll method doesn’t seems to accept Comparator object.
I know another solution is to iterate through the lists and find the common ones. I am looking if there is already some method which do it.
Thanks.
I don’t know of any cleaner way than what you already suggest.
However, if you need equality but can’t use
equals(I’m not going to ask 😉 you could merge the lists and sort them, and then compare manually each element to the next, keeping only the duplicate ones.