Java Stream API: Functional Pipelines, Transformations & Reductions
Learn Java 8+ Stream API with practical examples: filter, map, flatMap, sorted, distinct, reduce, Collectors.groupingBy, and parallel streams.
Java
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamApiTutorial {
public record Developer(String name, String skill, int yearsExp) {}
public static void main(String[] args) {
List<Developer> devs = Arrays.asList(
new Developer("Vikas", "Java", 6),
new Developer("Sneha", "Python", 4),
new Developer("Karan", "Java", 8),
new Developer("Pooja", "React", 3)
);
// Group senior developers by primary skill
Map<String, List<Developer>> groupedBySkill = devs.stream()
.filter(d -> d.yearsExp() >= 4)
.collect(Collectors.groupingBy(Developer::skill));
groupedBySkill.forEach((skill, list) -> {
System.out.println(skill + ": " + list.stream().map(Developer::name).toList());
});
}
}
1. Streams vs. Collections
A collection is an in-memory data structure that holds elements, while a Stream is a computational pipeline that processes elements on-demand. Streams do not mutate their underlying source; they yield transformations lazily.
2. Intermediate vs. Terminal Operations
Stream pipelines consist of two distinct types of operations:
- Intermediate Operations: (e.g.
filter(),map(),flatMap(),sorted()) Return another Stream and execute lazily. No computation happens until a terminal operation is called. - Terminal Operations: (e.g.
collect(),forEach(),reduce(),count()) Trigger traversal of the pipeline and produce a concrete result or side-effect.
Key Engineering Takeaways
- Streams are single-use; once a terminal operation executes, the stream cannot be reused.
- Prefer method references (Class::method) for concise functional code.
- Use parallelStream() judiciously only for CPU-bound computations on large datasets.
Frequently Asked Questions
What is the difference between map() and flatMap()?
map() transforms each element into a single value, while flatMap() transforms each element into a stream and flattens multiple streams into a single consolidated stream.
Master This in Our Ghaziabad Coding Labs
Gain deep mastery over these concepts with direct instructor guidance, code reviews, and mock interviews at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.
Explore Related Course Call 7503962162