What is the collection.stream() method in java?

Overview

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.

Syntax

The syntax of the collection.stream() method is:

Stream<E> Collection.stream() // This method does not take any parameters.
Syntax of the Collection.stream() method

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.

Code example

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 list
Stream<Integer> stream = list.stream();
// Print each element in the stream
stream.forEach(System.out::println);
}
}

Explanation

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 as Stream.findFirst(), Stream.reduce(), or Stream.toArray().

When to use streams

Streams should be used when:

  • We need to perform a set of operations on a data set.
  • The data set is too large to fit in memory.
  • We want to perform a lazy evaluation (avoid unnecessary computation).

When not to use streams

Streams should not be used when:

  • The data set is small enough to fit in memory.
  • We only need to perform a single operation on the data set.
  • We need to mutate the data set (for example, with the Stream.sorted() method).

Note: If you only need to perform a single operation on a small data set, it is better to use a for loop.

Free Resources