COLLECTIONS-306. Added predicated subtract method to CollectionUtils.

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/collections/trunk@1127123 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Brent Worden 2011-05-24 16:11:07 +00:00
parent 0543f907c1
commit 99be993a40
2 changed files with 41 additions and 1 deletions

View File

@ -33,6 +33,7 @@ import org.apache.commons.collections.collection.SynchronizedCollection;
import org.apache.commons.collections.collection.TransformedCollection;
import org.apache.commons.collections.collection.UnmodifiableBoundedCollection;
import org.apache.commons.collections.collection.UnmodifiableCollection;
import org.apache.commons.collections.functors.TruePredicate;
/**
* Provides utility methods and decorators for {@link Collection} instances.
@ -235,11 +236,32 @@ public class CollectionUtils {
* @see Collection#removeAll
*/
public static <O> Collection<O> subtract(final Iterable<? extends O> a, final Iterable<? extends O> b) {
Predicate<O> p = TruePredicate.truePredicate();
return subtract(a, b, p);
}
/**
* Returns a new {@link Collection} containing <i>a</i> minus a subset of
* <i>b</i>. Only the elements of <i>b</i> that satisfy the predicate
* condition, <i>p</i> are subtracted from <i>a</i>.
*
* @param a the collection to subtract from, must not be null
* @param b the collection to subtract, must not be null
* @param p the condition used to determine which elements of <i>b</i> are
* subtracted.
* @param <O> the generic type that is able to represent the types contained
* in both input collections.
* @return a new collection with the results
* @see Collection#removeAll
*/
public static <O> Collection<O> subtract(final Iterable<? extends O> a, final Iterable<? extends O> b, final Predicate<O> p) {
ArrayList<O> list = new ArrayList<O>();
addAll(list, a);
for (O element : b) {
if (p.evaluate(element)) {
list.remove(element);
}
}
return list;
}

View File

@ -361,6 +361,24 @@ public class TestCollectionUtils extends MockTestCase {
assertNull(freq2.get(1));
}
@Test
public void testSubtractWithPredicate() {
// greater than 3
Predicate<Number> predicate = new Predicate<Number>() {
public boolean evaluate(Number n) {
return n.longValue() > 3L;
}
};
Collection<Number> col = CollectionUtils.subtract(iterableA, collectionC, predicate);
Map<Number, Integer> freq2 = CollectionUtils.getCardinalityMap(col);
assertEquals(Integer.valueOf(1), freq2.get(1));
assertEquals(Integer.valueOf(2), freq2.get(2));
assertEquals(Integer.valueOf(3), freq2.get(3));
assertEquals(Integer.valueOf(2), freq2.get(4));
assertNull(freq2.get(5));
}
@Test
public void testIsSubCollectionOfSelf() {
assertTrue(CollectionUtils.isSubCollection(collectionA, collectionA));