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();
You have to consume the stream to find out if it's empty. That's the point of Stream's semantics (laziness). To check that the stream is not empty you have to attempt to consume at least one element. At that point the stream has lost its "virginity" and cannot be consumed again from the start.
If the Stream is empty (and it doesn't matter if it's empty due to the source of the stream being empty, or due to all the elements of the stream being filtered out prior to the terminal operation), the output List will be empty too. Save this answer. Show activity on this post. You will get a empty collection.
The isEmpty() method of List interface in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.
Return Value : Stream empty() returns an empty sequential stream. Note : An empty stream might be useful to avoid null pointer exceptions while callings methods with stream parameters.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With