简体   繁体   English

如何添加两个Optional<Long> 在 Java 中

[英]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这样,如果两者都为空,则总计应该为空,如果其中一个具有该值,则总计应该具有该值,如果它们都具有该值,那么它们应该被添加并存储在总计中

How about using Stream s?使用Stream怎么样?

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> .顺便说一句,我会使用OptionalLong而不是Optional<Long>

The solution would be similar:解决方案将是类似的:

OptionalLong total = Stream.of(totalLanding,totalSharing)
                           .filter(OptionalLong::isPresent)
                           .mapToLong(OptionalLong::getAsLong)
                           .reduce(Long::sum);

Java 9 or newer: Java 9 或更新版本:

Optional<Long>total = Stream.concat(
        totalLanding.stream(),
        totalSharing.stream())
    .reduce(Long::sum)

Java 8 compatible variant: Java 8 兼容变体:

Optional<Long>total = Stream.concat(
        totalLanding.map(Stream::of).orElseGet(Stream::empty),
        totalSharing.map(Stream::of).orElseGet(Stream::empty))
    .reduce(Long::sum)

Or better to extract the .map(Stream::of).orElseGet(Stream::empty) as a utility method and reuse.或者更好地提取.map(Stream::of).orElseGet(Stream::empty)作为实用方法.map(Stream::of).orElseGet(Stream::empty)用。 Or other variants here: How to convert an Optional<T> into a Stream<T>?或这里的其他变体: 如何将 Optional<T> 转换为 Stream<T>?

This should work with Java 8:这应该适用于 Java 8:

Optional<Long> total = totalLanding.map(x -> x + totalSharing.orElse(0L))
        .map(Optional::of)   // wrap it twice for the next line to find an Optional inside
        .orElse(totalSharing);

How about怎么样

BigDecimal zero = BigDecimal.ZERO

Optional<Long> addition = Optional.of(totalLanding.orElse(zero).add(totalSharing.orElse(zero)));

我们可以这样做:

Optional<Long>result = Optional.of((totalLanding != null ? totalLanding.get() : 0L) + (totalSharing != null ? totalSharing.get() : 0L));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM