smallufo smallufo - 6 months ago 47
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("found");
else
System.out.println("Not found");


But I think it is not so 'function style'

Optional has an '
ifPresent
' method , but unable to chain a '
orElse
' 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 Optional.map() works for the following case :

opt.map( o -> {
System.out.println("while opt is present...");
o.setProperty(xxx);
dao.update(o);
return null;
}).orElseGet( () -> {
System.out.println("create new obj");
dao.save(new 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.

Answer

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) {
        optional.ifPresent(c);
        return this;
    }

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

Then :

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