Java: How do I perform list operations with different definitions of equals?
Java: How do I perform list operations with different definitions of equals?
I have two lists of generic POJOs. I need to perform some set operations on the lists based on different ways of comparing the POJOs within the lists.
For example, if my POJO had the following structure:
public class GenericPojo {
private String id;
private String address;
private String city;
private String country;
private String extraDetails;
}
(with the appropriate getters and setters)
Given List1<GenericPojo> and List2<GenericPojo> , how would I find:
List1 - List2 (where the GenericPojo classes are equal if just the IDs are equal)
Intersect of List1 and List2 (where id , address , city , country , but not extraDetails of GenericPojo are equal)
Would two different custom comparator classes be helpful here? Are there any libraries that handle these operations effectively or should I try implementing my own?
If you must manipulate class out of your control, I would suggest using delegation. Here is my try:
RichList<T> wrapper around List s implementing the List contract, based on the decorator pattern. EqualityChecker<T> inteface, with a single method `public boolean equal( T t1, T, t2). EqualityChecker<T> concrete instance that will do the equality test for you. So you can add both operations to all existing List s for any kind of object for which you have written an EqualityChecker .
Further improvements: You can also write a default EqualityChecker<T> which just calls the equals method of the compared objects. You can then overload both new operations to default the EqualityChecker .
If your lists contain no duplicates (with repsect to the hypothetical custom comparator classes) you can use two TreeSets instead, instantiated with your two comparators respectively.
A drawback of this (apart from the duplication constraint) is that the order you get when iterating over elements depend on the comparators.
鉴于您对平等的具体要求, List#removeAll()和List#retainAll()将不符合您的需求,所以我认为您需要一个自定义实现来执行与这两种操作类似的操作。
