smallufo smallufo - 5 months ago 34x
Java Question

Functional style of Java 8's Optional.ifPresent and if-not-Present?

in java 8 , I want to do something to an optional object if it is present , and do another thing if it is not present.

if (opt.isPresent())
System.out.println("Not found");

But I think it is not so 'function style'

Optional has an '
' method , but unable to chain a '
' method.
So I cannot write :

opt.ifPresent( x -> System.out.println("found " + x))
.orElse( System.out.println("NOT FOUND"));

Is there any other way ?


Thanks @assylias , but I don't think works for the following case : o -> {
System.out.println("while opt is present...");
return null;
}).orElseGet( () -> {
System.out.println("create new obj"); obj);
return null;

In this case , when opt is present , I update its property and save to db; while it is not available , I create a new obj and save to db.

Note in the two lambdas , I have to return null.

But when opt is truly present , both lambdas will be executed. object will be updated , and a new object will be saved to db . This is because the
return null
in the first lambda. And orElseGet() will continue to execute.


For me the answer of @Dane White is OK, first I did not like using Runnable but I could not find any alternatives, here another implementation I preferred more

public class OptionalConsumer<T> {
    private Optional<T> optional;

    private OptionalConsumer(Optional<T> optional) {
        this.optional = optional;

    public static <T> OptionalConsumer<T> of(Optional<T> optional) {
        return new OptionalConsumer<>(optional);

    public OptionalConsumer<T> ifPresent(Consumer<T> c) {
        return this;

    public OptionalConsumer<T> ifNotPresent(Runnable r) {
        if (!optional.isPresent())
        return this;

Then :

Optional<Any> o = Optional.of(...);
OptionalConsumer.of(o).ifPresent(s ->System.out.println("isPresent "+s))
            .ifNotPresent(() -> System.out.println("! isPresent"));