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 {

    public void or() {
        int message = this.answer().
        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:

NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 7: Bootstrap, Effective, Architectures, Web, React and Angular, Testing and Microservices

Podcast: and newsletter:

A book about rethinking Java EE Patterns


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