Java Lambda - check if an ArrayList to Stream is e

2019-04-26 20:39发布

问题:

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();

回答1:

Stream.findFirst returns an Optional, its up to you to check if the optional has a value rather than just calling get.

You could use the orElse method to return a default value if the optional is empty.



回答2:

You should probably add what is the type of bonusScheduleDurationContainers. Also it is due to the findFirst().get Function. See the documentation. It states that there will be a exception. You should use orElse