1

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())
}
Rudrani Angira
  • 956
  • 2
  • 14
  • 28
  • Do you have list of values or just one value? Why would you want to use optional here? Check the source where Null is coming and if you can change that then you can think of the same. Look at this one https://stackoverflow.com/questions/23773024/functional-style-of-java-8s-optional-ifpresent-and-if-not-present – SMA Jul 03 '18 at 16:43
  • `value.getId()` returns single value. – Rudrani Angira Jul 03 '18 at 16:47
  • What's wrong with value.getErrorType() == null ? success.add(..) : failure.add(..); – SMA Jul 03 '18 at 16:49
  • I would like to modify above code using `Optional`. – Rudrani Angira Jul 03 '18 at 16:50
  • 1
    Possible duplicate of [Functional style of Java 8's Optional.ifPresent and if-not-Present?](https://stackoverflow.com/questions/23773024/functional-style-of-java-8s-optional-ifpresent-and-if-not-present) – SMA Jul 03 '18 at 16:53

1 Answers1

7

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());
Holger
  • 285,553
  • 42
  • 434
  • 765