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();
Magnus
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.
来源:https://stackoverflow.com/questions/34522637/java-lambda-check-if-an-arraylist-to-stream-is-empty