Java Streams: A Modern Way to Process Data
Introduced in Java 8, the Stream API brings a functional approach to processing collections. With streams, you can perform operations like filtering, mapping, and reducing in a concise and readable way.
🔍 What is a Stream?
A Stream represents a sequence of elements and supports sequential and parallel aggregate operations.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream()
.filter(name -> name.startsWith("A"))
.forEach(System.out::println);
Output: Alice
⚙️ Common Operations
1. filter()
Filters elements based on a condition:
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);
nums.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
2. map()
Transforms each element:
List<String> names = Arrays.asList("Java", "Python", "Go");
names.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
3. reduce()
Reduces the stream to a single value:
int sum = Stream.of(1, 2, 3, 4)
.reduce(0, Integer::sum);
System.out.println(sum);
Output: 10
🔁 Collecting Results
You can collect stream results into collections:
List<String> filtered = names.stream()
.filter(n -> n.length() > 3)
.collect(Collectors.toList());
🚀 Parallel Streams
Process elements in parallel using multiple threads:
list.parallelStream()
.filter( ... )
.map( ... )
.collect(Collectors.toList());
Use with care — not always faster depending on workload and thread management.
✅ Summary
- Streams make code cleaner and easier to read.
- They enable functional-style operations on collections.
- Use
map,filter,reduce,collectfor powerful transformations.
Java Streams = less boilerplate, more power. Try them in your next project!
Comments
Post a Comment