Java - Streams API in Java

1. What is the Streams API?

The Streams API, introduced in Java 8, is used to process collections of data such as lists or sets in a functional and efficient way. It allows developers to perform operations like filtering, mapping, sorting, and collecting data without writing complex loops.

A stream does not store data itself. Instead, it processes data from a source like a collection or array and produces a result.


2. Why Use Streams?

  • Reduces lengthy loop-based code

  • Improves readability and structure

  • Supports parallel processing

  • Works well with lambda expressions

  • Simplifies data manipulation

Example without streams:

for(String name : list){ if(name.startsWith("A")){ System.out.println(name); } }

With streams:

list.stream() .filter(name -> name.startsWith("A")) .forEach(System.out::println);

3. Basic Stream Processing Flow

Stream operations generally follow three steps:

  1. Source
    Data comes from a collection, array, or other structure.

  2. Intermediate Operations
    These transform or filter the data. Examples include:

    • filter()

    • map()

    • sorted()

  3. Terminal Operation
    Produces the final result. Examples include:

    • forEach()

    • collect()

    • count()

Once a terminal operation runs, the stream cannot be reused.


4. Common Stream Operations

filter() — Select elements based on a condition

list.stream() .filter(x -> x > 10) .forEach(System.out::println);

map() — Transform each element

list.stream() .map(x -> x * 2) .forEach(System.out::println);

sorted() — Sort elements

list.stream() .sorted() .forEach(System.out::println);

collect() — Store results into a collection

List result = list.stream() .filter(x -> x > 5) .collect(Collectors.toList());

5. Types of Streams

Sequential Stream
Processes elements one at a time.

list.stream()

Parallel Stream
Processes elements simultaneously using multiple threads.

list.parallelStream()

6. Advantages of Streams API

  • Cleaner and shorter code

  • Functional programming support

  • Easier data processing

  • Potential performance improvements

  • Integrates with lambda expressions


7. Important Notes

  • Streams do not modify the original collection

  • They can be used only once

  • Designed for processing, not storing data

    Summary

    The Streams API provides a modern approach to handling and processing data in Java collections. By replacing manual loops with declarative operations, it improves readability, efficiency, and maintainability of code.