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:
parent
86c4eea3dd
commit
23099cff16
|
@ -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");
|
||||
}
|
||||
}
|
|
@ -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() {
|
||||
|
|
Loading…
Reference in New Issue