BAEL-3994: Add example of chaining methods returning Optionals (#9102)

* BAEL-3994: Add example of chaining methods returning Optionals

* BAEL-3994: Update
This commit is contained in:
kwoyke 2020-04-15 21:19:02 +02:00 committed by GitHub
parent 86c4eea3dd
commit 23099cff16
2 changed files with 45 additions and 2 deletions

View File

@ -0,0 +1,21 @@
package com.baeldung.orelseoptional;
import java.util.Optional;
public class ItemsProvider {
Optional<String> getEmptyItem() {
System.out.println("Returning an empty item");
return Optional.empty();
}
Optional<String> getNail() {
System.out.println("Returning a nail");
return Optional.of("nail");
}
Optional<String> getHammer() {
System.out.println("Returning a hammer");
return Optional.of("hammer");
}
}

View File

@ -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<String> 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<String> 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() {