Skip to main content

Java Stream API Example in Java

1 min read Updated May 29, 2026
Share:
On this page (7sections)

Introduction

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

Example Program

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

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

  • Use streams for readability when the pipeline is short and clear.
  • Prefer traditional loops for complex branching or when performance tuning on hot paths.
  • Call stream() on the collection; do not reuse a consumed stream.

Common Mistakes

  • Forgetting that intermediate operations are lazy until a terminal operation runs.
  • Using parallel streams on small datasets where overhead exceeds benefit.

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