gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:02:42 25 4
gpt4 key购买 nike

我有以下lambda表达式,如果bonusScheduleDurationContainers不为空,则可以正常工作。如果为空,我得到一个NoSuchElementException。如何在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();

最佳答案

Stream.findFirst 返回 Optional ,它由您检查 optional 参数是否具有值,而不仅仅是调用get。

如果 optional 参数为空,则可以使用 orElse 方法返回默认值。

关于lambda - Java Lambda-检查要流的ArrayList是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34522637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com