Java Stream API Example in Java
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: 2Common Stream Operations
| Operation | Purpose |
|---|---|
filter | Keep elements matching a condition |
map | Transform each element |
sorted | Sort elements |
collect | Gather results into a list, set or map |
count | Count 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.
- Declare the variables that hold the program’s data.
- 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.