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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With