How to peek on an Optional?

With the new stream method in the Optional API as of JDK9, you can invoke the stream method to transform from Optional<T> to Stream<T> which then enables one to peek and then if you want to go back to the Optional<T> just invoke findFirst() or findAny().

an example in your case:

Optional.ofNullable(key)
        .map(Person::get) // Optional<Person>
        .stream() // Stream<Person>
        .peek(this::printName)
        .peek(this::printAddress)
        ...

Here's how you can implement the missing peek method for Optional:

<T> UnaryOperator<T> peek(Consumer<T> c) {
    return x -> {
        c.accept(x);
        return x;
    };
}

Usage:

Optional.ofNullable(key)
    .map(Person::get)
    .map(peek(this::printName))
    .map(peek(this::printAddress));

You can use this syntax:

ofNullable(key)
    .map(Person::get)
    .map(x -> {printName(x);return x;})
    .map(x -> {printAddress(x);return x;});

Tags:

Java

Optional