Reputation: 986
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
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