I am just wondering what will be behavior of Java 8 stream on empty list.
List<?> emptyList = new ArrayList<>(); List<?> processedList = emptyList.stream().collect(Collectors.toList());
Will this be empty list or null
?
I know streams do lazy propagation, so in this case will call go to collect()
method or just it will end at stream()
method?
toList()) , you'll always get an output List (you'll never get null ). 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.
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.
IntStream. of(new int[]{}) also returns an empty stream. The Arrays class has stream creation methods which accept an array of primitives or an object type. This can be used to create an empty stream; e.g.,: System.
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.
collect
is a terminal operation, so it must be evaluated.
When terminating a Stream
pipeline with collect(Collectors.toList())
, you'll always get an output List
(you'll never get null
). 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.
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