Monday, December 15, 2025

Stream API in Java

 The Stream API in Java, introduced in Java 8, is a powerful feature for processing sequences of objects in a functional and declarative way. It allows developers to perform operations like filtering, mapping, and reducing on collections without modifying the original data source. 

Key Concepts
  • Not a Data Structure: A stream is not a data structure that stores elements. It's a pipeline for operations, taking input from sources like collections, arrays, or I/O channels.
  • Functional Style: It enables writing concise and readable code using functional programming concepts (like lambda expressions and method references), often replacing verbose for or forEach loops.
  • Laziness: Intermediate operations are lazy; they are not executed until a terminal operation is invoked, which optimizes performance by processing only the necessary elements.
  • Non-Mutability: Streams do not modify the source collection, ensuring data integrity.
  • Parallelization: Streams can be easily run in parallel (parallelStream()) to leverage multi-core processors for improved performance with large datasets. 
The Three Parts of a Stream Operation
A typical stream pipeline involves three stages:
  1. Stream Creation: Obtaining a stream from a data source.
    • From a Collection (e.g., list.stream()).
    • From an Array (e.g., Arrays.stream(array)).
    • Using static methods (e.g., Stream.of(...)Stream.iterate(...)Stream.generate(...)).
  2. Intermediate Operations: These operations transform a stream into another stream and are lazily executed. They can be chained together to form a pipeline.
    • filter(): Selects elements based on a given predicate (condition).
    • map(): Transforms each element into a new value (e.g., converting strings to uppercase).
    • sorted(): Sorts the elements in the stream.
    • distinct(): Removes duplicate elements.
  3. Terminal Operation: This operation initiates the processing of the pipeline and produces a final result or side effect, ending the stream's lifecycle.
    • collect(): Gathers the processed elements into a new collection (e.g., Collectors.toList()).
    • forEach(): Performs an action on each element (e.g., printing to the console).
    • reduce(): Combines the elements into a single value.
    • count(): Returns the number of elements in the stream.
    • anyMatch()allMatch()noneMatch(): Check if elements match a given predicate. 
Example
java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Alice");

        // Using Stream API to filter, transform, and collect data
        List<String> uniqueNamesStartingWithA = names.stream()               // 1. Create stream
                                                     .filter(name -> name.startsWith("A")) // 2. Intermediate (filter)
                                                     .distinct()                         // 2. Intermediate (distinct)
                                                     .map(String::toUpperCase)           // 2. Intermediate (map)
                                                     .collect(Collectors.toList());      // 3. Terminal (collect)

        System.out.println(uniqueNamesStartingWithA); // Output: [ALICE]
    }
}
For more in-depth learning, you can explore tutorials and documentation on the official Dev.java website. 

This is  from the Google  AI Review 

No comments:

Post a Comment

Some interesting things to explore more

 Here  some  some  things  to  study  more ,     How Google Search works               https://developers.google.com/search/docs/fundamental...