Java 9: Executing fallbacks with Optional::or

Java 9 comes with an additional Optional.or method with the following functionality:

"If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function."

The method Optional::or is useful for the implementation of fallback logic. The example below return an Integer with the value 42:


import java.util.Optional;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;

public class OptionalTest {

    @Test
    public void or() {
        int message = this.answer().
                map(Integer::parseInt).
                or(this::defaultAnswer).
                get();
        assertThat(message, is(42));
    }

    public Optional<String> answer() {
        return Optional.ofNullable(null);
    }

    public Optional<Integer> defaultAnswer() {
        return Optional.of(42);
    }
}    

The method answer returns null, therefore the method map is not executed. The (fallback) or branch is executed instead and returns directly the 42 as integer.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


Cloudy Jakarta EE and MicroProfile: Microservices, Clouds and Beyond Jakarta EE / MicroProfile airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
realworldpatterns.com
...the last 150 posts
...the last 10 comments
License