Java Lambda - 检查ArrayList to Stream是否为空 [英] Java Lambda - check if an ArrayList to Stream is empty
本文介绍了Java Lambda - 检查ArrayList to Stream是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下lambda表达式,如果 bonusScheduleDurationContainers
不为空,则工作正常。如果它是空的,我得到一个 NoSuchElementException
。我如何在lambda表达式中检查这个?
I have the following lambda expression and if works fine when bonusScheduleDurationContainers
is not empty. If it is empty, I get a NoSuchElementException
. How do I check this in the lambda expression?
final List<ScheduleDurationContainer> bonusScheduleDurationContainers
= scheduleDurationContainersOfWeek.stream()
.filter(s -> s.getContainerType() == ScheduleIntervalContainerTypeEnum.BONUS)
.collect(Collectors.toList());
final ScheduleDurationContainer bonusScheduleDurationContainer
= bonusScheduleDurationContainers.stream()
.filter(s -> s.getDayOfWeekStartingWithZero() == dayOfWeekTmp)
.findFirst()
.get();
推荐答案
Stream.findFirst
返回 可选
,由您来检查可选项是否具有值而不是仅调用get。
Stream.findFirst
returns an Optional
, its up to you to check if the optional has a value rather than just calling get.
您可以使用 orElse
方法,如果可选项为空,则返回默认值。
You could use the orElse
method to return a default value if the optional is empty.
这篇关于Java Lambda - 检查ArrayList to Stream是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文