Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Lambda - check if an ArrayList to Stream is empty

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();
like image 449
quma Avatar asked Dec 30 '15 03:12

quma


People also ask

How do I know if my stream is empty?

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.

Can we stream an empty List?

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.

How do you know if an optional List is empty?

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.

What happens if stream is empty Java?

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.


2 Answers

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.

like image 103
Magnus Avatar answered Oct 25 '22 17:10

Magnus


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

like image 33
Aseem Bansal Avatar answered Oct 25 '22 17:10

Aseem Bansal