Java Stream API — Quick Guide
The Stream API was introduced in Java 8. It is used to process collections of data in a declarative way using operations such as filter(), map(), sorted(), and collect().
Basic flow
List<Integer> numbers = Arrays.asList(10, 15, 20, 25, 30);
List<Integer> result = numbers.stream()
.filter(n -> n > 20)
.map(n -> n * 2)
.collect(Collectors.toList());
System.out.println(result);
Output:
[50, 60]
Think of it as:
Collection → Stream → Intermediate operations → Terminal operation → Result
Important Stream API operations
| Operation | Purpose | Example |
|---|---|---|
filter() | Select elements | filter(x -> x > 10) |
map() | Transform elements | map(x -> x * 2) |
sorted() | Sort elements | sorted() |
distinct() | Remove duplicates | distinct() |
limit() | Take first N | limit(5) |
skip() | Skip first N | skip(2) |
forEach() | Process elements | forEach(System.out::println) |
collect() | Convert to collection/result | collect(Collectors.toList()) |
count() | Count elements | count() |
reduce() | Combine elements | reduce(0, Integer::sum) |
anyMatch() | Check if any match | anyMatch(x -> x > 50) |
allMatch() | Check if all match | allMatch(x -> x > 0) |
findFirst() | Get first element | findFirst() |
filter() vs map()
List<String> names = Arrays.asList("Ram", "John", "Raj", "David");
names.stream()
.filter(name -> name.length() > 3)
.forEach(System.out::println);
filter() removes/selects elements.
names.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
map() transforms elements.
reduce() example
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, (a, b) -> a + b);
System.out.println(sum);
Output:
15
Very important interview point
Intermediate operations are lazy. They don't execute until a terminal operation is invoked.
numbers.stream()
.filter(n -> n > 10)
.map(n -> n * 2);
Nothing is actually processed yet.
Adding:
.forEach(System.out::println);
causes the pipeline to execute.
Common interview question
What is the difference between map() and flatMap()?
map() transforms each element into another element:
List<List<Integer>> data =
Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4)
);
data.stream()
.map(list -> list)
flatMap() flattens nested structures:
List<Integer> result = data.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
System.out.println(result);
Output:
[1, 2, 3, 4]
Comments
Post a Comment