Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream operation on empty list

Tags:

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?

like image 533
gaurav agarwal Avatar asked Feb 03 '19 09:02

gaurav agarwal


People also ask

Does stream work on empty List?

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.

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.

How do you create an empty stream in Java?

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.

How do you check a List is empty or not in Java 8?

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.


1 Answers

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.

like image 175
Eran Avatar answered Sep 29 '22 09:09

Eran