diff --git a/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java b/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java new file mode 100644 index 0000000000..480dc782e4 --- /dev/null +++ b/core-java-modules/core-java-optional/src/main/java/com/baeldung/orelseoptional/ItemsProvider.java @@ -0,0 +1,21 @@ +package com.baeldung.orelseoptional; + +import java.util.Optional; + +public class ItemsProvider { + + Optional getEmptyItem() { + System.out.println("Returning an empty item"); + return Optional.empty(); + } + + Optional getNail() { + System.out.println("Returning a nail"); + return Optional.of("nail"); + } + + Optional getHammer() { + System.out.println("Returning a hammer"); + return Optional.of("hammer"); + } +} \ No newline at end of file diff --git a/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java b/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java index 91aebbeebd..e3bdedcd82 100644 --- a/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java +++ b/core-java-modules/core-java-optional/src/test/java/com/baeldung/orelseoptional/OrElseOptionalUnitTest.java @@ -1,10 +1,10 @@ package com.baeldung.orelseoptional; -import static org.junit.Assert.assertEquals; +import org.junit.Test; import java.util.Optional; -import org.junit.Test; +import static org.junit.Assert.assertEquals; public class OrElseOptionalUnitTest { @@ -25,6 +25,28 @@ public class OrElseOptionalUnitTest { assertEquals(fallbackOptionalString, OptionalUtils.or(optionalString, fallbackOptionalString)); } + @Test + public void givenTwoOptionalMethods_whenFirstEmpty_thenSecondEvaluated() { + ItemsProvider itemsProvider = new ItemsProvider(); + + Optional item = itemsProvider.getEmptyItem() + .map(Optional::of) + .orElseGet(itemsProvider::getNail); + + assertEquals(Optional.of("nail"), item); + } + + @Test + public void givenTwoOptionalMethods_whenFirstNonEmpty_thenSecondNotEvaluated() { + ItemsProvider itemsProvider = new ItemsProvider(); + + Optional item = itemsProvider.getNail() + .map(Optional::of) + .orElseGet(itemsProvider::getHammer); + + assertEquals(Optional.of("nail"), item); + } + // Uncomment code when code base is compatible with Java 9 // @Test // public void givenOptional_whenEmptyValue_thenCustomMessage() {