Rudrani Angira
Rudrani Angira

Reputation: 986

java 8: Using Optional with lambda

How can I code the logic below using Optional and lambda? I have two Lists

List success = new ArrayList<>();
List failures = new ArrayList<>();

And there is an object

RoomTypes value

for which value.getErrorType() could be NULL or not and value.getId() returns integer.

I would like to update success and failure with value.getId() list according to value.getErrorType() being null.

Something like:

if(value.getErrorType().equals(NULL)){
   success.add(value.getId())
}
else{
   failure.add(value.getId())
}

Upvotes: 1

Views: 8874

Answers (1)

Holger
Holger

Reputation: 298579

Assuming, NULL actually means null, you can use

Optional.ofNullable(value.getErrorType())
        .map(x -> failure).orElse(success).add(value.getId());

though it is not recommend to use Optional for such a case, as a similar ordinary check is straight-forward:

(value.getErrorType() == null? success: failure).add(value.getId());

Upvotes: 7

Related Questions