Back to Study Material Java

Stream API in Java

The Stream API, introduced in Java 8, provides a functional approach to processing sequences of data. A Stream is not a data structure; it does not store e...

Stream API in Java

Processing Data Pipelines with Streams

The Stream API, introduced in Java 8, provides a functional approach to processing sequences of data. A Stream is not a data structure; it does not store elements. Instead, it is a pipeline of operations that processes data from a source such as a Collection, array, or I/O channel. Streams support lazy evaluation, meaning intermediate operations are not executed until a terminal operation is invoked.

A stream pipeline has three parts. First, a source such as list.stream() or Arrays.stream(array). Second, zero or more intermediate operations that transform the stream: filter(), map(), flatMap(), sorted(), distinct(), peek(), and limit(). These return a new stream and are lazy. Third, a terminal operation that triggers processing and produces a result: collect(), forEach(), reduce(), count(), findFirst(), anyMatch(), and toList().

List<String> names = List.of("Alice", "Bob", "Charlie", "Anna", "Brian"); List<String> result = names.stream() .filter(n -> n.startsWith("A")) .map(String::toUpperCase) .sorted() .collect(Collectors.toList()); System.out.println(result); // [ALICE, ANNA]

Streams can be sequential or parallel. Calling parallelStream() or stream().parallel() enables multi-threaded processing automatically, distributing work across available CPU cores. Parallel streams are beneficial for large datasets with independent operations but can introduce overhead and ordering issues for small collections.

The Collectors utility class offers powerful terminal collection strategies: Collectors.groupingBy() groups elements by a classifier, Collectors.joining() concatenates strings, Collectors.toMap() collects into a Map, and Collectors.partitioningBy() splits into two groups based on a predicate.

Streams are one-use only. Once a terminal operation is called, the stream is consumed and cannot be reused.

Interview tip: A common interview question is the difference between map() and flatMap(). The answer is that map() applies a function and wraps each result in a stream, while flatMap() flattens the resulting streams into a single stream. Use flatMap() when each element produces a collection that you want to merge.