java / intermediate
Snippet
Stream API for Collection Processing
Streams allow functional-style operations on sequences of elements, such as filtering, mapping, and reducing collections efficiently.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.List;import java.util.stream.Collectors;public class StreamExample {public static void main(String[] args) {List<String> names = List.of("Anna", "Bob", "Charlie", "David");List<String> filtered = names.stream().filter(n -> n.length() > 4).collect(Collectors.toList());System.out.println(filtered);}}
Breakdown
1
.filter(n -> n.length() > 4)
An intermediate operation that selects elements matching a predicate.
2
.collect(Collectors.toList())
A terminal operation that transforms the stream back into a List.