Sobes.tech
Junior

What is a Stream in the context of Stream API?

sobes.tech AI

Answer from AI

Stream in the context of Java Stream API is a sequence of elements on which various operations can be performed.

Main characteristics of Stream API:

  • Not a data structure: Stream does not store data but works with it as needed.
  • Lazy: Intermediate operations are executed only when a terminal operation is invoked.
  • Consumed once: After executing a terminal operation, the stream is considered exhausted and cannot be reused.
  • Supports operation pipelines: Intermediate operations return a new stream, allowing the creation of chains (pipelines).

Example of usage:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

// Creating a list of numbers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// Using Stream API to filter even numbers and collect them into a new list
List<Integer> evenNumbers = numbers.stream() // Creating a stream from the list
                                 .filter(n -> n % 2 == 0) // Intermediate operation: filtering
                                 .collect(Collectors.toList()); // Terminal operation: collecting into a list

// Outputting the result (for demonstration)
// evenNumbers.forEach(System.out::println);

Types of operations:

Operation Type Description Examples
Intermediate Returns a new stream. Lazy. Can be chained in a pipeline. filter(), map(), sorted(), distinct()
Terminal Produces a final result. Does not return a stream. Ends the pipeline. forEach(), collect(), reduce(), count(), anyMatch()

Stream API allows writing more declarative and readable code for processing data collections.

What is a Stream in the context of Stream API? — Java - sobes.tech