☕ Java
Stream API in Java 8
The Stream API completely changed how Java developers work with collections. Instead of writing for loops and if statements to filter, transform, and aggregate data, you chain descriptive operations. It reads like a SQL query, runs efficiently, and handles parallelism for free.
What is a Stream?
A Stream is a pipeline for processing a sequence of elements. It's NOT a data structure — it doesn't store data. It processes data from a source (collection, array, file) through a series of operations and produces a result.
Two types of operations:
• Intermediate — transform or filter the stream and return a new stream. Lazy — don't execute until a terminal operation triggers them. Examples: filter(), map(), sorted(), distinct(), limit()
• Terminal — trigger execution and produce a result. Examples: collect(), forEach(), count(), reduce(), findFirst()
Key insight: Streams are lazy. Nothing runs until you call a terminal operation. This allows Java to optimize the pipeline under the hood.
Stream Operations — Practical Examples
Java
import java.util.*;
import java.util.stream.*;
List<String> employees = Arrays.asList(
"Alice-Engineering", "Bob-Marketing", "Charlie-Engineering",
"Diana-HR", "Eve-Engineering"
);
// filter — keep only Engineering employees
List<String> engineers = employees.stream()
.filter(e -> e.contains("Engineering"))
.collect(Collectors.toList());
// [Alice-Engineering, Charlie-Engineering, Eve-Engineering]
// map — extract just the names
List<String> names = employees.stream()
.map(e -> e.split("-")[0]) // take part before "-"
.collect(Collectors.toList());
// [Alice, Bob, Charlie, Diana, Eve]
// sorted + distinct
List<Integer> scores = Arrays.asList(85, 92, 85, 78, 92, 65);
List<Integer> uniqueSorted = scores.stream()
.distinct()
.sorted()
.collect(Collectors.toList());
// [65, 78, 85, 92]
// reduce — aggregate to a single value
int total = scores.stream().reduce(0, Integer::sum); // 497
// count — how many pass a filter
long highScorers = scores.stream().filter(s -> s >= 85).count(); // 4
// anyMatch / allMatch / noneMatch — boolean checks
boolean hasFailure = scores.stream().anyMatch(s -> s < 60); // falseRelated Topics in Java 8 Features
Lambda Expressions
Java 8's lambdas let you pass behavior as data — write functions inline, without the ceremony of anonymous classes. They make your code dramatically shorter and more expressive, especially when working with collections.
Optional Class
NullPointerException has been called 'the billion dollar mistake'. Optional is Java's solution: a wrapper that forces you to think about whether a value might be absent, instead of blindly assuming it exists.