假设我的代码中有以下可选参数:
Optional<Integer> a = Optional.of(1);
Optional<Integer> b = Optional.of(1);
Optional<Integer> c = Optional.of(1);如果它们(a、b和c)都存在,我需要实现一些逻辑。我如何才能以一种优雅的方式做到这一点?
我需要这样做(举个例子):
...
if (a.isPresent() && b.isPresent() && c.isPresent()) {
return a.get() + b.get() + c.get();
}
...发布于 2019-07-23 22:59:26
这里:
Optional<Integer> a = Optional.of(1);
Optional<Integer> b = Optional.of(1);
Optional<Integer> c = Optional.of(1);问题是:当你像那样声明“独立”变量时,你必须处理它们(编写代码!)“独立”也是如此。
换句话说:要么使用Stream.of()或Arrays.asList(a, b, c)之类的东西进行进一步处理;要么在创建时直接将这些“常量”放入列表/数组中。
因为只有这样你才能转向流逻辑,正如Luis在评论中所概述的那样。
发布于 2019-07-23 22:59:34
您可以从所有这些内容创建流,并执行reduce操作:
Stream.of(a, b, c)
.filter(Optional::isPresent)
.map(Optional::get)
.mapToInt(Integer::intValue)
.sum();https://stackoverflow.com/questions/57166830
复制相似问题