1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Java Streams Api
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
17Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Java Streams Api

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
17Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Streams API

Overview

The Java Streams API (introduced in Java 8) revolutionized how Java developers process collections of data. A Stream is a sequence of elements from a source (like a List or array) that supports a pipeline of operations to transform, filter, or aggregate that data. It is not a data structure — it doesn't store data. It is a computation model.

Streams are designed around a three-phase pipeline: 1. Source: Where the stream originates (list.stream(), Arrays.stream(arr), Stream.of(...)). 2. Intermediate Operations: Lazy transformations that return a new Stream (filter, map, sorted, distinct, limit). They are lazy — they do nothing until a terminal operation is called. 3. Terminal Operations: They trigger the entire pipeline and produce a result or side effect (collect, count, forEach, reduce, findFirst, anyMatch).

Streams are by default lazy — intermediate operations are not executed until a terminal operation demands results. This means chaining 5 intermediate operations doesn't traverse the data 5 times; it traverses once with all 5 operations applied per element. This makes Streams highly efficient. They also support Parallel Streams (parallelStream()) to automatically leverage multi-core CPUs.

Syntax

Notice how stream pipelines are declarative. You declare what you want to achieve, rather than writing the manual loops to specify how to iterate over the data.

Building a Stream Pipeline
java
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(5, 2, 8, 1, 9, 3, 7, 4, 6, 10);
        
        // 1. Full Pipeline: filter → sort → map → collect
        List<String> result = numbers.stream()
            .filter(n -> n > 5)              // Keep only 6, 7, 8, 9, 10
            .sorted()                        // Sort ascending: 6, 7, 8, 9, 10
            .map(n -> "Item #" + n)          // Transform: "Item #6", etc.
            .collect(Collectors.toList());   // Terminal: collect to List
        
        System.out.println(result);
        
        // 2. Aggregation Operations
        int total = numbers.stream()
            .reduce(0, Integer::sum);        // Sum all elements
        System.out.println("Total: " + total); // 55
        
        long count = numbers.stream()
            .filter(n -> n % 2 == 0)         // Even numbers
            .count();                         // Count them
        System.out.println("Even count: " + count); // 5
        
        // 3. Short-circuiting Terminal Operations
        boolean anyOver8 = numbers.stream().anyMatch(n -> n > 8); // true
        Optional<Integer> first = numbers.stream()
            .filter(n -> n > 7)
            .findFirst();                    // Optional[8]
        
        // 4. Numeric Streams (Avoid Boxing!)
        double avg = numbers.stream()
            .mapToInt(Integer::intValue)     // IntStream (no boxing)
            .average()
            .orElse(0);
        System.out.println("Average: " + avg); // 5.5
    }
}

Common Pitfalls

  • Reusing a Stream after a terminal operation has consumed it. A Stream can only be traversed ONCE. Calling stream.count() and then stream.forEach(...) will throw IllegalStateException: stream has already been operated upon or closed. Always create a fresh stream from the source for each terminal operation.
  • Using parallel streams carelessly. While parallelStream() sounds like a free performance win, it introduces the overhead of thread pool management and splitting/merging data. For small lists or collections whose processing is CPU-intensive, parallel streams are far slower than sequential. Only use them after profiling with large data sets.
  • Performing side effects inside intermediate operations. map() and filter() are supposed to be pure functions — they should not modify external state. Doing list.stream().forEach(item -> externalList.add(item)) inside map() causes confusing behavior due to Streams' lazy and potentially parallel nature. Use collect() for aggregation instead.

Interview Questions

What is the difference between an Intermediate and a Terminal operation in a Stream pipeline?

Intermediate operations (like filter(), map(), sorted()) are lazy — they don't process any data when called. They just record the operation to be applied. Terminal operations (like collect(), count(), forEach()) trigger the entire pipeline, processing all elements through all recorded intermediate operations in a single traversal.

What is the difference between map() and flatMap() in Streams?

map() transforms each element into exactly one output element (1-to-1 transformation). flatMap() transforms each element into a Stream of zero or more elements, then flattens all those streams into a single stream (1-to-many). It is used for operations like splitting a list of sentences into a stream of individual words.

When would you prefer IntStream, LongStream, or DoubleStream over Stream<Integer>?

The specialized primitive streams (IntStream, LongStream, DoubleStream) avoid autoboxing/unboxing, which creates Integer/Long/Double wrapper objects in the heap for every element. For numeric-heavy computations on large datasets, primitive streams can be 3-5x faster and generate far less garbage for the JVM's GC.

Real-World Example

Data transformation pipelines are a perfect fit for Streams. Processing a batch of orders from a database — filtering only shipped orders, extracting the total revenue per customer, and sorting the results — is expressed as a clean, readable, and highly optimized stream pipeline.

example
java
// Processing thousands of orders efficiently
Map<String, Double> revenueByCustomer = orders.stream()
    .filter(order -> order.getStatus() == SHIPPED)
    .filter(order -> order.getAmount() > 0)
    .collect(Collectors.groupingBy(
        Order::getCustomerId,
        Collectors.summingDouble(Order::getAmount)
    ));

// Sorted leaderboard by revenue
revenueByCustomer.entrySet().stream()
    .sorted(Map.Entry.<String, Double>comparingByValue().reversed())
    .limit(10)
    .forEach(e -> System.out.println(e.getKey() + ": $" + e.getValue()));

Check Your Knowledge

Test your understanding of Streams API with these quick questions.

Question 1

Intermediate operations in the Streams API are described as 'lazy'. What does this mean?

Question 2

Which of the following is a Terminal operation that triggers the stream pipeline?

Question 3

What happens if you call two terminal operations on the same Stream object?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Streams API

Overview

The Java Streams API (introduced in Java 8) revolutionized how Java developers process collections of data. A Stream is a sequence of elements from a source (like a List or array) that supports a pipeline of operations to transform, filter, or aggregate that data. It is not a data structure — it doesn't store data. It is a computation model.

Streams are designed around a three-phase pipeline: 1. Source: Where the stream originates (list.stream(), Arrays.stream(arr), Stream.of(...)). 2. Intermediate Operations: Lazy transformations that return a new Stream (filter, map, sorted, distinct, limit). They are lazy — they do nothing until a terminal operation is called. 3. Terminal Operations: They trigger the entire pipeline and produce a result or side effect (collect, count, forEach, reduce, findFirst, anyMatch).

Streams are by default lazy — intermediate operations are not executed until a terminal operation demands results. This means chaining 5 intermediate operations doesn't traverse the data 5 times; it traverses once with all 5 operations applied per element. This makes Streams highly efficient. They also support Parallel Streams (parallelStream()) to automatically leverage multi-core CPUs.

Syntax

Notice how stream pipelines are declarative. You declare what you want to achieve, rather than writing the manual loops to specify how to iterate over the data.

Building a Stream Pipeline
java
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(5, 2, 8, 1, 9, 3, 7, 4, 6, 10);
        
        // 1. Full Pipeline: filter → sort → map → collect
        List<String> result = numbers.stream()
            .filter(n -> n > 5)              // Keep only 6, 7, 8, 9, 10
            .sorted()                        // Sort ascending: 6, 7, 8, 9, 10
            .map(n -> "Item #" + n)          // Transform: "Item #6", etc.
            .collect(Collectors.toList());   // Terminal: collect to List
        
        System.out.println(result);
        
        // 2. Aggregation Operations
        int total = numbers.stream()
            .reduce(0, Integer::sum);        // Sum all elements
        System.out.println("Total: " + total); // 55
        
        long count = numbers.stream()
            .filter(n -> n % 2 == 0)         // Even numbers
            .count();                         // Count them
        System.out.println("Even count: " + count); // 5
        
        // 3. Short-circuiting Terminal Operations
        boolean anyOver8 = numbers.stream().anyMatch(n -> n > 8); // true
        Optional<Integer> first = numbers.stream()
            .filter(n -> n > 7)
            .findFirst();                    // Optional[8]
        
        // 4. Numeric Streams (Avoid Boxing!)
        double avg = numbers.stream()
            .mapToInt(Integer::intValue)     // IntStream (no boxing)
            .average()
            .orElse(0);
        System.out.println("Average: " + avg); // 5.5
    }
}

Common Pitfalls

  • Reusing a Stream after a terminal operation has consumed it. A Stream can only be traversed ONCE. Calling stream.count() and then stream.forEach(...) will throw IllegalStateException: stream has already been operated upon or closed. Always create a fresh stream from the source for each terminal operation.
  • Using parallel streams carelessly. While parallelStream() sounds like a free performance win, it introduces the overhead of thread pool management and splitting/merging data. For small lists or collections whose processing is CPU-intensive, parallel streams are far slower than sequential. Only use them after profiling with large data sets.
  • Performing side effects inside intermediate operations. map() and filter() are supposed to be pure functions — they should not modify external state. Doing list.stream().forEach(item -> externalList.add(item)) inside map() causes confusing behavior due to Streams' lazy and potentially parallel nature. Use collect() for aggregation instead.

Interview Questions

What is the difference between an Intermediate and a Terminal operation in a Stream pipeline?

Intermediate operations (like filter(), map(), sorted()) are lazy — they don't process any data when called. They just record the operation to be applied. Terminal operations (like collect(), count(), forEach()) trigger the entire pipeline, processing all elements through all recorded intermediate operations in a single traversal.

What is the difference between map() and flatMap() in Streams?

map() transforms each element into exactly one output element (1-to-1 transformation). flatMap() transforms each element into a Stream of zero or more elements, then flattens all those streams into a single stream (1-to-many). It is used for operations like splitting a list of sentences into a stream of individual words.

When would you prefer IntStream, LongStream, or DoubleStream over Stream<Integer>?

The specialized primitive streams (IntStream, LongStream, DoubleStream) avoid autoboxing/unboxing, which creates Integer/Long/Double wrapper objects in the heap for every element. For numeric-heavy computations on large datasets, primitive streams can be 3-5x faster and generate far less garbage for the JVM's GC.

Real-World Example

Data transformation pipelines are a perfect fit for Streams. Processing a batch of orders from a database — filtering only shipped orders, extracting the total revenue per customer, and sorting the results — is expressed as a clean, readable, and highly optimized stream pipeline.

example
java
// Processing thousands of orders efficiently
Map<String, Double> revenueByCustomer = orders.stream()
    .filter(order -> order.getStatus() == SHIPPED)
    .filter(order -> order.getAmount() > 0)
    .collect(Collectors.groupingBy(
        Order::getCustomerId,
        Collectors.summingDouble(Order::getAmount)
    ));

// Sorted leaderboard by revenue
revenueByCustomer.entrySet().stream()
    .sorted(Map.Entry.<String, Double>comparingByValue().reversed())
    .limit(10)
    .forEach(e -> System.out.println(e.getKey() + ": $" + e.getValue()));

Check Your Knowledge

Test your understanding of Streams API with these quick questions.

Question 1

Intermediate operations in the Streams API are described as 'lazy'. What does this mean?

Question 2

Which of the following is a Terminal operation that triggers the stream pipeline?

Question 3

What happens if you call two terminal operations on the same Stream object?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A