Friday, 6 September 2013

How to retainAll, but regarding doubles in Java?

How to retainAll, but regarding doubles in Java?

Suppose I have two ArrayLists with both having some objects in it:
Object a = new Object();
Object b = new Object();
Object c = new Object();
Object d = new Object();
ArrayList list1 = new ArrayList();
list1.add(a);
list1.add(a);
list1.add(a);
list1.add(b);
list1.add(b);
list1.add(c);
ArrayList list2 = new ArrayList();
list2.add(a);
list2.add(a);
list2.add(b);
list2.add(c);
list2.add(c);
list2.add(d);
ArrayList output = retainAllButRegardingDoubles(list1, list2);
Now I want to find the elements which intersect with the elements in the
other array, but regarding doubles. With 'regarding doubles' I mean this:
if list 1 contains three times object A, and list 2 contains twice object
A, then the returning array will contain twice object A, because object A
occurs at least twice in both arrays.
So I want the outputting list to be as follows:
ArrayList {
a,
a,
b,
c
}
'a' occurs in both lists twice, 'b' once and 'c' once.
Is there a library for doing that or do I have to write it myself? If yes,
how?

No comments:

Post a Comment