Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a implementation of retainAll() with custom Comparators?

I need to sift Collections according to contents of other Collections. Usually, I would have used the Collection.retainAll() method.

Unfortunately, the equality of the domain objects I am handling is rather volatile, depending on the comparison context. Thus, I cannot rely on equals/hashCode.

My next reflex was to use a custom Comparator, but I was unable to find any methods supporting what I had in mind. Implementing the functionality is not a problem but I feel like reinventing the wheel here.

Have I missed something in the API? Other frameworks (not too esoteric) like commons are welcome too.
And if not, what optimizations would make my straightforward impl (creating a list of all Objects inside both Collections by going over all items of both Collections in n^2) a good one?

like image 774
kostja Avatar asked Oct 17 '11 14:10

kostja


2 Answers

Suggest using Guava's filter. Alternative is to roll your own retainAllBy(sourceCollection, Comparator).

like image 165
andersoj Avatar answered Sep 27 '22 16:09

andersoj


Guava has a cumbersome solution to this problem, the Equivalence concept. You wrap your objects in an equivalence using Equivalence.wrap(), store the wrapped versions in collections and thereby make the collections use your custom equals / hashcode logic.

I (and others) have requested Equivalence-based sets and maps, but unfortunately the Guava team suggests that the above route should be taken instead.

like image 32
Sean Patrick Floyd Avatar answered Sep 27 '22 16:09

Sean Patrick Floyd