From 824828087154b9b5e83dc07626dfba708f6c7241 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andreas=20Z=C3=B6llner?= Date: Mon, 13 Feb 2023 09:31:52 +0100 Subject: [PATCH] add ThrowingPredicate functions to default to true or false on exception for filtering streams --- .../pivovarit/function/ThrowingPredicate.java | 22 +++++++++++++++++++ .../function/ThrowingPredicateTest.java | 22 +++++++++++++++++-- 2 files changed, 42 insertions(+), 2 deletions(-) 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