Skip to content

Commit

Permalink
Added containsBy to RichIterable. Closes #919.
Browse files Browse the repository at this point in the history
Signed-off-by: Donald Raab <Donald.Raab@bnymellon.com>
  • Loading branch information
donraab committed Jul 7, 2020
1 parent cb8b03c commit 759d4f5
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
Expand Up @@ -17,6 +17,7 @@
import java.util.LongSummaryStatistics;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
Expand Down Expand Up @@ -179,6 +180,23 @@ default T getOnly()
*/
boolean contains(Object object);

/**
* Returns true if the iterable has an element which responds true to element.equals(value)
* after applying the specified function to the element.
*
* @since 10.3
*/
default <V> boolean containsBy(
Function<? super T, ? extends V> function,
V value)
{
Objects.requireNonNull(function);
Predicate<? super T> predicate = null == value
? each -> null == function.valueOf(each)
: each -> value.equals(function.valueOf(each));
return this.anySatisfy(predicate);
}

/**
* Returns true if all elements in source are contained in this collection.
*
Expand Down
Expand Up @@ -160,6 +160,7 @@
import org.eclipse.collections.impl.set.mutable.primitive.ShortHashSet;
import org.eclipse.collections.impl.set.sorted.mutable.TreeSortedSet;
import org.eclipse.collections.impl.test.Verify;
import org.eclipse.collections.impl.tuple.Tuples;
import org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples;
import org.junit.Assert;
import org.junit.Test;
Expand Down Expand Up @@ -192,6 +193,31 @@ public void contains()
Assert.assertFalse(collection.contains(5));
}

@Test
public void containsBy()
{
MutableList<Pair<Integer, String>> list =
Lists.mutable.with(
Tuples.pair(1, "1"),
Tuples.pair(2, "2"),
Tuples.pair(3, null));

Assert.assertTrue(
list.containsBy(Pair::getTwo, "2"));
Assert.assertFalse(
list.containsBy(Pair::getTwo, "3"));
Assert.assertTrue(
list.containsBy(Pair::getTwo, null));
Assert.assertFalse(
list.containsBy(Pair::getOne, null));
Assert.assertFalse(
list.newEmpty().containsBy(Pair::getOne, null));
Assert.assertFalse(
list.newEmpty().containsBy(Pair::getOne, "2"));
Verify.assertThrows(NullPointerException.class, () ->
list.newEmpty().containsBy(null, "2"));
}

@Test
public void containsAllIterable()
{
Expand Down

0 comments on commit 759d4f5

Please sign in to comment.