You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@commons.apache.org by Ludwig Magnusson <lu...@mediatool.com> on 2012/05/13 13:02:12 UTC

[Collections] retainAll and removeAll with different equal-methods

Hello!
I have two lists and I want to use the methods ListUtils.retainAll and ListUtils.removeAll on them. However, I want to do this several times with comparison methods that are different from the defaul equals-method. I.e I would like to compare the elements in the two lists from several different prespectives. 

Consider a class Person that has the attributes firstName and lastName. I could define the equals method to say that two persons equals if they have the same first name. I could also say that they equals if they have the same full name. But what if I want to alternate?

So basically what I want to do is this:
List<Person> firstList; 
List<Person> secondList;
List<Person> firstNamesThatOccurInBothLists = ListUtils.retainAll(firstList, secondList, [Third equals-comparator argument]);
List<Person> fullNamesThatOccurInBothLists = ListUtils.retainAll(firstList, secondList, [Third equals-comparator argument]);

Can something of this effect be done with commons collections in any way?
/Ludwig

Re: [Collections] retainAll and removeAll with different equal-methods

Posted by James Carman <ja...@carmanconsulting.com>.
You might want to try CollectionUtils.filter() using a Predicate.

On Sun, May 13, 2012 at 7:02 AM, Ludwig Magnusson <lu...@mediatool.com> wrote:
> Hello!
> I have two lists and I want to use the methods ListUtils.retainAll and ListUtils.removeAll on them. However, I want to do this several times with comparison methods that are different from the defaul equals-method. I.e I would like to compare the elements in the two lists from several different prespectives.
>
> Consider a class Person that has the attributes firstName and lastName. I could define the equals method to say that two persons equals if they have the same first name. I could also say that they equals if they have the same full name. But what if I want to alternate?
>
> So basically what I want to do is this:
> List<Person> firstList;
> List<Person> secondList;
> List<Person> firstNamesThatOccurInBothLists = ListUtils.retainAll(firstList, secondList, [Third equals-comparator argument]);
> List<Person> fullNamesThatOccurInBothLists = ListUtils.retainAll(firstList, secondList, [Third equals-comparator argument]);
>
> Can something of this effect be done with commons collections in any way?
> /Ludwig

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@commons.apache.org
For additional commands, e-mail: user-help@commons.apache.org