diff --git a/src/main/java/com/pivovarit/function/ThrowingPredicate.java b/src/main/java/com/pivovarit/function/ThrowingPredicate.java index bb1086a..44c3b47 100644 --- a/src/main/java/com/pivovarit/function/ThrowingPredicate.java +++ b/src/main/java/com/pivovarit/function/ThrowingPredicate.java @@ -44,6 +44,28 @@ static Predicate unchecked(ThrowingPredicate predicate) { }; } + static Predicate uncheckedFalse(ThrowingPredicate predicate) { + requireNonNull(predicate); + return t -> { + try { + return predicate.test(t); + } catch (final Exception e) { + return false; + } + }; + } + + static Predicate uncheckedTrue(ThrowingPredicate predicate) { + requireNonNull(predicate); + return t -> { + try { + return predicate.test(t); + } catch (final Exception e) { + return true; + } + }; + } + /** * @return Predicate instance that rethrows the checked exception using the Sneaky Throws pattern */ diff --git a/src/test/java/com/pivovarit/function/ThrowingPredicateTest.java b/src/test/java/com/pivovarit/function/ThrowingPredicateTest.java index 68afa3f..139a72b 100644 --- a/src/test/java/com/pivovarit/function/ThrowingPredicateTest.java +++ b/src/test/java/com/pivovarit/function/ThrowingPredicateTest.java @@ -4,8 +4,7 @@ import java.util.stream.Stream; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.*; class ThrowingPredicateTest { @@ -36,4 +35,23 @@ void shouldWrapInRuntimeExWhenUsingStandardUtilsFunctions() { .hasMessage(cause.getMessage()) .hasCause(cause); } + + @Test + void returnValueWhenExceptionOccurs() { + Exception cause = new Exception("some message"); + + // given + ThrowingPredicate predicate = i -> { + throw cause; + }; + + // when + assertThatCode(() -> Stream.of(42).anyMatch(i -> ThrowingPredicate.uncheckedFalse(predicate).test(i))) + .doesNotThrowAnyException(); + assertThatCode(() -> Stream.of(42).anyMatch(i -> ThrowingPredicate.uncheckedTrue(predicate).test(i))) + .doesNotThrowAnyException(); + + assertThat(Stream.of(42).anyMatch(i -> ThrowingPredicate.uncheckedFalse(predicate).test(i))).isFalse(); + assertThat(Stream.of(42).anyMatch(i -> ThrowingPredicate.uncheckedTrue(predicate).test(i))).isTrue(); + } } \ No newline at end of file