Java Stream API

Introduction

The Java Stream API is one of the most powerful features introduced in Java 8. It provides a modern and functional approach to processing collections of data. Instead of writing lengthy loops and conditional statements, developers can use the Stream API to perform operations such as filtering, sorting, mapping, searching, reducing, and collecting data with concise and readable code.

A stream is not a data structure. It does not store data; instead, it processes data from a source such as a collection, array, or input/output channel. Streams support functional programming by working with Lambda Method References.

For example, instead of writing multiple loops to filter employees with salaries greater than ₹50,000, you can achieve the same result using a single stream pipeline.

What is the Java Stream API?

The Java Stream API is a feature that allows developers to process sequences of elements in a declarative and functional style.

A stream:

  • Does not store data
  • Processes data from a source
  • Supports sequential and parallel operations
  • Can perform filtering, mapping, sorting, reducing, and collecting
  • Is consumed after execution

A stream can be created from:

  • Collections
  • Arrays
  • Files
  • Input streams
  • Generated values

Why Do We Need Stream API?

Before Java 8:


List names = A*rrays.asList("Rahul", "Amit", "Neha");
for(String name : names) {
    if(name.startsWith("R")) {
        System.out.println(name);
    }
}

Using Stream API:


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

The Stream API reduces boilerplate code and improves readability.

Features of Stream API

Some important features are:

  • Introduced in Java 8
  • Supports functional programming
  • Works with Lambda Expressions
  • Supports sequential and parallel processing
  • Improves readability
  • Reduces boilerplate code
  • Supports lazy evaluation
  • Provides built-in operations
  • Does not modify the original collection
  • Easy integration with Collections Framework

How Stream API Works

A Stream pipeline generally consists of three stages:

  1. Source
  2. Intermediate Operations
  3. Terminal Operation

Example:


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

Pipeline:


Collection
      ↓
Stream
      ↓
Intermediate Operations
      ↓
Terminal Operation
      ↓
Result

Syntax

Creating a stream:


Collection.stream();

Example:


List list =
        Arrays.asList("Java", "Python", "C++");
Stream stream = list.stream();

Creating Streams

From a Collection


List numbers =
        Arrays.asList(10,20,30);
numbers.stream();

From an Array


String[] names =
        {"Rahul","Amit","Neha"};
Arrays.stream(names);

Using Stream.of()


Stream stream =
        Stream.of("Java","Python","C++");

Infinite Stream


Stream numbers =
        Stream.iterate(1,n -> n+1);

Intermediate Operations

Intermediate operations return another stream and are lazy, meaning they execute only when a terminal operation is called.

Common intermediate operations:

Method Description
filter() Filters elements
map() Transforms elements
sorted() Sorts elements
distinct() Removes duplicates
limit() Limits elements
skip() Skips elements
peek() Performs an action for debugging

Terminal Operations

Terminal operations produce a final result or side effect.

Common terminal operations:

Method Description
forEach() Iterates over elements
collect() Collects results
count() Counts elements
reduce() Reduces to a single value
findFirst() Returns first element
anyMatch() Checks condition
allMatch() Checks all elements
noneMatch() Checks no elements
min() Finds minimum
max() Finds maximum

Example 1: Filtering Elements


import java.util.*;
public class Main {
    public static void main(String[] args) {
        List numbers =
                Arrays.asList(10,20,30,40,50);
        numbers.stream()
                .filter(number -> number > 25)
                .forEach(System.out::println);
    }
}

Output

30
40
50

Example 2: Mapping Elements


import java.util.*;
public class Main {
    public static void main(String[] args) {
        List names =
                Arrays.asList("java","python","c++");
        names.stream()
                .map(String::toUpperCase)
                .forEach(System.out::println);
    }
}

Output

JAVA
PYTHON
C++

Example 3: Sorting Elements


import java.util.*;
public class Main {
    public static void main(String[] args) {
        List numbers =
                Arrays.asList(50,20,10,40);
        numbers.stream()
                .sorted()
                .forEach(System.out::println);
    }
}

Output

10
20
40
50

Example 4: Removing Duplicate Elements


import java.util.*;
public class Main {
    public static void main(String[] args) {
        List numbers =
                Arrays.asList(10,20,20,30,30,40);
        numbers.stream()
                .distinct()
                .forEach(System.out::println);
    }
}

Output

10
20
30
40

Example 5: Collecting Results


import java.util.*;
import java.util.stream.Collectors;
public class Main {
    public static void main(String[] args) {
        List names =
                Arrays.asList("Java","Python","C++");
        List result =
                names.stream()
                     .map(String::toUpperCase)
                     .collect(Collectors.toList());
        System.out.println(result);
    }
}

Output

[JAVA, PYTHON, C++]

Example 6: Counting Elements


long count =
numbers.stream()
       .filter(number -> number > 20)
       .count();
System.out.println(count);

Output

3

Example 7: Finding Maximum Value


Optional max = numbers.stream().max(Integer::compare);
System.out.println(max.get());

Output

50

Example 8: Using reduce()


int sum = numbers.stream().reduce(0,Integer::sum);
System.out.println(sum);

Output

150

Parallel Stream

Java Stream API supports parallel processing.

Sequential Stream:


list.stream();

Parallel Stream:


list.parallelStream();

Example:


numbers.parallelStream()
       .forEach(System.out::println);

Parallel streams improve performance for large datasets on multi-core processors.

Stream API vs Collection

Stream Collection
Processes data Stores data
Lazy evaluation Immediate storage
Supports functional programming Traditional programming
Cannot modify source Stores elements
One-time use Can be reused
Supports parallel processing No built-in parallel processing

Stream API vs Loop

Loop Stream API
More code Less code
Manual iteration Automatic iteration
Harder to read More readable
Limited chaining Supports chaining
Difficult parallel processing Easy parallel processing

Real-life Example

Imagine an Employee Management System.

Employee List:


Rahul - 60000
Amit - 40000
Neha - 70000

Using Stream API:


employees.stream()
         .filter(employee ->
                 employee.getSalary() > 50000)
         .sorted(
             Comparator.comparing(Employee::getSalary)
         )
         .forEach(System.out::println);

Other real-world applications include:

  • Banking systems
  • E-commerce platforms
  • Student management systems
  • Inventory management
  • Data analytics
  • Report generation
  • Log processing
  • Financial applications

Advantages of Stream API

  • Less boilerplate code
  • Improved readability
  • Functional programming support
  • Easy filtering and sorting
  • Supports parallel processing
  • Lazy evaluation improves performance
  • Integrates well with Lambda Expressions
  • Simplifies collection processing

Limitations of Stream API

  • Streams cannot be reused after a terminal operation.
  • Not suitable for modifying the source collection directly.
  • Parallel streams may not always improve performance for small datasets.
  • Complex stream pipelines can become difficult to debug.

Common Mistakes

1. Reusing a Stream

Incorrect:


Stream stream = list.stream();
stream.forEach(System.out::println);
stream.forEach(System.out::println);

This throws an IllegalStateException.

Always create a new stream when needed.

2. Forgetting the Terminal Operation

Incorrect:


numbers.stream()
       .filter(number -> number > 20);

Nothing happens because no terminal operation is present.

Correct:


numbers.stream()
       .filter(number -> number > 20)
       .forEach(System.out::println);

3. Modifying the Source Collection During Stream Processing

Avoid modifying the collection while iterating through a stream, as it can lead to unexpected behavior or exceptions.

4. Overusing Parallel Streams

Parallel streams are beneficial for large datasets and CPU-intensive tasks. Using them for small collections may reduce performance because of thread management overhead.

5. Using Complex Lambdas

Keep lambda expressions simple. Move complex business logic into separate methods to improve readability and maintainability.

Best Practices

  • Use streams for data processing rather than simple iteration.
  • Keep stream pipelines short and readable.
  • Prefer method references when possible.
  • Use collect() to create new collections instead of modifying existing ones.
  • Use parallel streams only after measuring performance benefits.
  • Avoid side effects inside stream operations.
  • Handle Optional values safely when using methods like findFirst(), min(), and max().

Time Complexity

The Stream API itself does not define fixed time complexity. It depends on the operations performed.

Operation Time Complexity
filter() O(n)
map() O(n)
sorted() O(n log n)
distinct() O(n)
count() O(n)
reduce() O(n)
collect() O(n)
min() / max() O(n)

Conclusion

The Java Stream API is one of the most valuable additions to modern Java development. It enables developers to process collections efficiently using a functional programming approach with Lambda Expressions, Method References, and Functional Interfaces. By providing operations such as filter(), map(), sorted(), reduce(), and collect(), the Stream API significantly reduces boilerplate code while improving readability and maintainability.

Related Java Tutorials