Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional ifPresent Return another type [duplicate]

With java 8 Optional, Is there a way to write this line of code:

Bar bar = fooOpt.isPresent() ? new Bar(fooOpt.get().getX()) : null;

something like:

Bar bar = fooOpt.ifPresent(f -> new Bar(f.getX()), null)
like image 316
Manolo Avatar asked Dec 22 '16 11:12

Manolo


1 Answers

Perhaps you are looking for:

    Optional<Foo> fooOpt = ...
    Bar bar = fooOpt.map(foo -> new Bar(foo.getX()))
                    .orElse(null);

Given:

public class Foo {
    Object getX() {
        ...
    }
}

public class Bar {

    public Bar(Object x) {
        ...
    }
}
like image 53
Harmlezz Avatar answered Nov 19 '22 10:11

Harmlezz