diff --git a/README.md b/README.md index 794140f..8e674ad 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ Then, you can add the dependency to your project. com.github.VassilisSoum FunctionalUtils - 2.4.0 + 2.8.0 ``` diff --git a/pom.xml b/pom.xml index afc6586..81907db 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.soumakis FunctionalUtils - 2.4.0 + 2.8.0 jar diff --git a/src/main/java/com/soumakis/control/Either.java b/src/main/java/com/soumakis/control/Either.java index 8189d5b..7c28991 100644 --- a/src/main/java/com/soumakis/control/Either.java +++ b/src/main/java/com/soumakis/control/Either.java @@ -363,4 +363,12 @@ default Either biFlatMap(Function } return rightFn.apply(getRight()); } + + default Either filterOrElse(Function predicate, + Supplier supplier) { + if (isRight() && predicate.apply(getRight())) { + return Either.right(getRight()); + } + return Either.left(supplier.get()); + } } diff --git a/src/main/java/com/soumakis/control/Try.java b/src/main/java/com/soumakis/control/Try.java index beb4f27..32bf0e6 100644 --- a/src/main/java/com/soumakis/control/Try.java +++ b/src/main/java/com/soumakis/control/Try.java @@ -196,6 +196,10 @@ default Either toEither() { return fold(Either::left, Either::right); } + default Either toEither(Supplier leftSupplier) { + return fold(__ -> Either.left(leftSupplier.get()), Either::right); + } + /** * Applies a function to the value if this is a {@code Success}, or a different function if this * is a {@code Failure}. diff --git a/src/test/java/com/soumakis/control/EitherTest.java b/src/test/java/com/soumakis/control/EitherTest.java index b3f4d95..f29f34c 100644 --- a/src/test/java/com/soumakis/control/EitherTest.java +++ b/src/test/java/com/soumakis/control/EitherTest.java @@ -168,4 +168,12 @@ void testBiFlatMapRight() { assert (mapped.getRight() == 2); } + @Test + void testFilterOrElse() { + Either right = Either.right(42); + Either filtered = right.filterOrElse(n -> n > 42, () -> "error"); + assert (filtered.isLeft()); + assert (filtered.getLeft().equals("error")); + } + }