Java Lambda-检查流的ArrayList是否为空

Java Lambda-检查流的ArrayList是否为空,lambda,java-8,java-stream,optional,Lambda,Java 8,Java Stream,Optional,我有以下lambda表达式,当bonusScheduleDurationContainers不为空时,if可以正常工作。如果它是空的,我会得到一个NoTouchElementException。如何在lambda表达式中检查此项 final List<ScheduleDurationContainer> bonusScheduleDurationContainers = scheduleDurationContainersOfWeek.stream()

我有以下lambda表达式,当
bonusScheduleDurationContainers
不为空时,if可以正常工作。如果它是空的,我会得到一个
NoTouchElementException
。如何在lambda表达式中检查此项

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();
最终列表bonusScheduleDurationContainers
=ScheduleDurationContainerOfWeek.stream()
.filter(s->s.getContainerType()==ScheduleIntervalContainerTypeEnum.BONUS)
.collect(Collectors.toList());
最终ScheduleDurationContainer bonusScheduleDurationContainer
=bonusScheduleDurationContainers.stream()
.filter(s->s.getDayOfWeekStartingWithZero()==dayOfWeekTmp)
.findFirst()
.get();

您可能应该添加bonusScheduleDurationContainers的类型。这也是由于findFirst().get函数造成的。请参阅文档。它说会有一个。您应该使用

返回一个,这取决于您检查可选项是否有值,而不仅仅是调用get

如果可选项为空,则可以使用该方法返回默认值