dulikkk
dulikkk

Reputation: 186

How to use return keyword in lambda

I have Optional. I want to write code which sounds as follows: If object is present convert him from Optional to Object and do remaining code with him. If is not present, return code 404. I try do this but is not working. I do not know how to use return statement here.

Object objectFromOptional = optional.stream()
                .findFirst().orElse(return ResponseEntity.notFound().build());

Upvotes: 2

Views: 317

Answers (2)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60046

No need return keyword, You can just use :

Object objectFromOptional = optional.stream()
                .findFirst()
                .orElse(ResponseEntity.notFound().build());

Edit

After OP comment, the suggested solution can be :

private static final ResponseEntity<Object> notFound = ResponseEntity.notFound().build(); 
...
Object objectFromOptional = optional
                .orElse(notFound);

Or as mentioned in the comments you can use orElseGet which took a Supplier like so :

Object objectFromOptional = optional
        .orElseGet(() -> ResponseEntity.notFound().build());

Upvotes: 3

Nidhish Krishnan
Nidhish Krishnan

Reputation: 20751

You can simply use like this without return and optional.stream()

Object objectFromOptional = optional.orElse(ResponseEntity.notFound().build());

Note: As @Andy mentioned, ResponseEntity.notFound().build() might be an expensive operation

Upvotes: 0

Related Questions