The collection.stream()
method returns a sequential Stream, with this collection as its source. The elements of the stream are only visited when the terminal operation is performed on the stream. This method performs a lazy evaluation, which allows for efficient processing of large data sets by avoiding unnecessary computation.
For example, if we have a large list of objects and we only need to process the first 10 elements, there is no need to evaluate the remaining elements.
The syntax of the collection.stream()
method is:
Stream<E> Collection.stream() // This method does not take any parameters.
In Stream<E> Collection.stream()
, E
is the type of elements in the collection. The stream can be used to filter, map, reduce, or perform other operations on the data set.
Here is the code example using the collection.stream()
method:
import java.util.*;import java.util.stream.*;public class Main {public static void main(String[] args) {List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);// Create a stream from the listStream<Integer> stream = list.stream();// Print each element in the streamstream.forEach(System.out::println);}}
Line 6: We create a list of type integer.
Line 9: We create a stream from the list.
Line 12: We print each element in the stream.
Note: It is important to note that the
Collection.stream()
method creates a new stream every time it is called. Therefore, it is not recommended to use this method within a loop. If we need to process the same data set multiple times, it is better to create a stream once and reuse it. We can also use other terminal methods such asStream.findFirst()
,Stream.reduce()
, orStream.toArray()
.
Streams should be used when:
Streams should not be used when:
Note: If you only need to perform a single operation on a small data set, it is better to use a
for
loop.