Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add two Optional<Long> in java

Optional<Long>totalLanding= ....(get it from somewhere);
Optional<Long>totalSharing = ...(get it from somewhere);

I want to do something like this not syntactically but logically

Optional<Long>total = totalLanding+totalSharing;

Such that if both are empty then total should be empty if one of them has the value then total should have that value is both of them have the value then they should get added and stored in total

like image 410
bhoomeendra Avatar asked Nov 17 '25 08:11

bhoomeendra


1 Answers

How about using Streams?

Optional<Long> total = Stream.of(totalLanding,totalSharing)
                             .filter(Optional::isPresent)
                             .map(Optional::get)
                             .reduce(Long::sum);

BTW, I'd use OptionalLong instead of Optional<Long>.

The solution would be similar:

OptionalLong total = Stream.of(totalLanding,totalSharing)
                           .filter(OptionalLong::isPresent)
                           .mapToLong(OptionalLong::getAsLong)
                           .reduce(Long::sum);
like image 165
Eran Avatar answered Nov 18 '25 21:11

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!