What are the main operations available in the Stream API?

 Tale of Contents

Introduction

The Stream API in Java provides a variety of operations that enable functional-style processing of sequences of elements, such as collections. These operations can be categorized into two main types: intermediate operations and terminal operations. Understanding these operations is key to effectively utilizing the Stream API for data manipulation and transformation.

1. Intermediate Operations

Intermediate operations are those that return a new stream and can be chained together. They are lazy, meaning they do not execute until a terminal operation is invoked.

Common Intermediate Operations

  • **filter(Predicate<? super T> predicate)**: Filters elements based on a given condition.

    Example:

  • **map(Function<? super T, ? extends R> mapper)**: Transforms each element in the stream using the provided function.

    Example:

  • **flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)**: Flattens nested streams into a single stream.

    Example:

  • **distinct()**: Removes duplicate elements from the stream.

    Example:

  • **sorted()**: Sorts the elements in natural order or according to a provided comparator.

    Example:

2. Terminal Operations

Terminal operations produce a result or side effect and terminate the stream. Once a terminal operation is called, the stream cannot be reused.

Common Terminal Operations

  • **collect(Collector<? super T, A, R> collector)**: Converts the elements of the stream into a different form, such as a list, set, or map.

    Example:

  • **forEach(Consumer<? super T> action)**: Performs an action for each element in the stream.

    Example:

  • **reduce(T identity, BinaryOperator<T> accumulator)**: Combines elements of the stream into a single result using an associative accumulation function.

    Example:

  • **findFirst()**: Returns the first element of the stream, wrapped in an Optional.

    Example:

  • **count()**: Returns the count of elements in the stream.

    Example:

Conclusion

The Stream API in Java offers a rich set of operations that enable developers to process and manipulate data in a functional style. By understanding the distinction between intermediate and terminal operations, you can effectively utilize the Stream API to perform complex data transformations and computations with clarity and efficiency. Whether you’re filtering, mapping, reducing, or collecting data, the Stream API provides powerful tools for handling collections and sequences in Java.

Similar Questions