Skip to main content
Browse topics

Java Stream API Example in Java

2 min read Updated May 29, 2026
Share

Introduction

The Stream API (Java 8+) supports declarative processing of collections — filtering, transforming and aggregating data in a pipeline without explicit loops.

Example Program

java
import java.util.*;
import java.util.stream.*;

public class StreamApiDemo {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(3, 8, 1, 10, 4, 6, 15);

        // Filter evens, square them, sort, collect
        List<Integer> result = numbers.stream()
                .filter(n -> n % 2 == 0)
                .map(n -> n * n)
                .sorted()
                .collect(Collectors.toList());

        System.out.println("Original : " + numbers);
        System.out.println("Pipeline : " + result);

        // String pipeline
        List<String> words = Arrays.asList("java", "stream", "api", "example");
        long count = words.stream()
                .filter(w -> w.length() > 4)
                .count();

        System.out.println("Words with length > 4: " + count);
    }
}

Sample Output

plaintext
Original : [3, 8, 1, 10, 4, 6, 15]
Pipeline : [16, 36, 64, 100]
Words with length > 4: 2

Common Stream Operations

OperationPurpose
filterKeep elements matching a condition
mapTransform each element
sortedSort elements
collectGather results into a list, set or map
countCount elements after intermediate operations

Best Practices

Common Mistakes

How It Works

This Java program demonstrates Stream API. It first prepares the data it needs, then performs the core operation step by step, and finally prints the output shown in the Sample Output above.

  1. Declare the variables that hold the program’s data.
  2. Print the final result to the console so you can compare it with the sample output.

Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.

Frequently Asked Questions

Do streams modify the original collection?
No. Stream operations produce new results. The source collection remains unchanged unless you explicitly mutate it outside the pipeline.
What is the difference between map and flatMap?
map transforms each element to one result. flatMap transforms each element to a stream and then flattens those streams into a single stream.

Related tutorials

Search tutorials