等价于Java流中的continue关键字?
上面的代码可以转换成Java流代码吗?我在等价于Java流中的continue关键字?,java,java-8,java-stream,Java,Java 8,Java Stream,上面的代码可以转换成Java流代码吗?我在continue关键字中遇到一个错误…只是为了扩展提供的答案,您也可以这样做 for (final Prices ppr : prices) { if (!currency.getCode().equals(ppr.getCurrency().getCode())) { continue; } return ppr.getPrice(); } return prices.stream() .filt
continue
关键字中遇到一个错误…只是为了扩展提供的答案,您也可以这样做
for (final Prices ppr : prices) {
if (!currency.getCode().equals(ppr.getCurrency().getCode())) {
continue;
}
return ppr.getPrice();
}
return prices.stream()
.filter(ppr -> currency.getCode().equals(ppr.getCurrent().getCode()))
.findFirst()
.orElseThrow(NoSuchElementException::new);
而不是.findFirst().get(),后者返回不应为空的值。因此,它假设将返回一些数据。使用orElse语句,您可以在不返回任何内容的情况下提供默认值。添加
货币
必须是最终的或有效的最终值。您不需要这样做。orElseThrow(NoSuchElementException::new);如果没有任何值,get()将抛出异常。@george这是风格问题。我宁愿避免Optional.get()
,因为它隐藏了结果的可选性。@JohnKugelman John在这里有一个观点。甚至有人在讨论中反对Java9中的Optionial.get()。看,我已经改正了。从docs get()返回:此可选项持有的非空值将抛出异常。它假定该值为非null,但OP需要orElse提供一个默认结果,在您提供的示例中,continue
是完全不必要的。
return prices.stream()
.filter(ppr -> currency.getCode().equals(ppr.getCurrent().getCode()))
.findFirst()
.orElse(/* provide some default Price in case nothing is returned */);