Java Lambda - check if an ArrayList to Stream is empty

流过昼夜 提交于 2019-12-22 04:12:57

问题


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



来源:https://stackoverflow.com/questions/34522637/java-lambda-check-if-an-arraylist-to-stream-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!