Skip to content

Commit

Permalink
Implement Optional.ifPresentOrElse.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 585727393
  • Loading branch information
Googler authored and copybara-github committed Nov 27, 2023
1 parent cff83e5 commit 1f564eb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
8 changes: 8 additions & 0 deletions jre/java/java/util/Optional.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ public void ifPresent(Consumer<? super T> consumer) {
}
}

public void ifPresentOrElse(Consumer<? super T> consumer, Runnable emptyConsumer) {
if (isPresent()) {
consumer.accept(ref);
} else {
emptyConsumer.run();
}
}

public Optional<T> filter(Predicate<? super T> predicate) {
checkNotNull(predicate);
if (!isPresent() || predicate.test(ref)) {
Expand Down
32 changes: 32 additions & 0 deletions jre/javatests/com/google/j2cl/jre/java8/util/OptionalTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,38 @@ public void testIfPresent() {
assertTrue("Consumer not executed", mutableFlag[0]);
}

public void testIfPresentOrElse() {
if (isWasm()) {
// TODO(b/183769034): Re-enable when NPE on dereference is supported
return;
}

// empty case
empty.ifPresentOrElse(null, () -> {}); // should not fail as per JavaDoc
empty.ifPresentOrElse(wrapped -> fail("Empty Optional should not execute consumer"), () -> {});

// non-empty case
try {
present.ifPresentOrElse(null, () -> {});
fail("Non-Empty Optional must throw NullPointerException if consumer is null");
} catch (NullPointerException e) {
// expected
}

present.ifPresentOrElse(
(wrapped) -> {
assertSame(REFERENCE, wrapped);
mutableFlag[0] = true;
},
() -> fail("Non-Empty Optional should not call empty consumer"));
assertTrue("Consumer not executed", mutableFlag[0]);
mutableFlag[0] = false;
empty.ifPresentOrElse(
(wrapped) -> fail("Empty Optional should not call non-empty consumer"),
() -> mutableFlag[0] = true);
assertTrue("Consumer not executed", mutableFlag[0]);
}

public void testFilter() {
if (isWasm()) {
// TODO(b/183769034): Re-enable when NPE on dereference is supported
Expand Down

0 comments on commit 1f564eb

Please sign in to comment.