The Streams API processes collections as a pipeline of steps: take the data, filter it, transform it, then collect a result. Instead of writing loops with temporary variables, you describe what you want, such as “the names of the top two students with CGPA above 3.5”, and the stream does the iteration. This lesson covers the common operations and the powerful Collectors for grouping and summarising.
In this lesson you will learn
- How a stream pipeline is built: source, intermediate and terminal operations
filter,map,sorted,distinctandlimit- Numeric streams:
sum,average,max - Matching with
anyMatchandallMatch - Grouping and partitioning with
Collectors
Streams use lambda expressions throughout, so read that lesson first if lambdas are new to you.
Building a Pipeline
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(4, 11, 8, 3, 15, 6, 8);
List<Integer> evensSquared = nums.stream()
.filter(n -> n % 2 == 0) // keep evens
.map(n -> n * n) // square them
.collect(Collectors.toList());
System.out.println(evensSquared);
int sum = nums.stream().mapToInt(Integer::intValue).sum();
double avg = nums.stream().mapToInt(n -> n).average().orElse(0);
System.out.println("sum=" + sum + " avg=" + String.format("%.2f", avg));
System.out.println(nums.stream().distinct().sorted().toList());
System.out.println(nums.stream().anyMatch(n -> n > 10) + " "
+ nums.stream().allMatch(n -> n > 0));
System.out.println(nums.stream().max(Integer::compare).get());
System.out.println(nums.stream().map(String::valueOf).collect(Collectors.joining(", ", "[", "]")));
}
}
Output
[16, 64, 36, 64]
sum=55 avg=7.86
[3, 4, 6, 8, 11, 15]
true true
15
[4, 11, 8, 3, 15, 6, 8]
- Every pipeline has three parts: a source (
nums.stream()), zero or more intermediate operations (filter,map) and one terminal operation (collect,sum,toList). - Intermediate operations are lazy: nothing runs until the terminal operation is called.
mapToIntconverts to anIntStream, which hassum()andaverage().average()returns anOptionalDoublebecause an empty stream has no average;orElse(0)supplies a fallback.distinct()removes duplicates andsorted()sorts.toList()(Java 16+) collects into an unmodifiable list.anyMatchandallMatchstop as soon as the answer is known.Collectors.joiningbuilds one string from many.- Streams do not change the source list;
numsis untouched.
Grouping With Collectors
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Main {
record Student(String name, String dept, double cgpa) {}
public static void main(String[] args) {
List<Student> students = List.of(
new Student("Nusrat", "CSE", 3.82), new Student("Arif", "EEE", 3.41),
new Student("Tania", "CSE", 3.95), new Student("Imran", "BBA", 3.10),
new Student("Mitu", "CSE", 3.67), new Student("Rafi", "EEE", 2.98));
Map<String, Long> countByDept = students.stream()
.collect(Collectors.groupingBy(Student::dept, TreeMap::new, Collectors.counting()));
System.out.println(countByDept);
Map<String, Double> avgByDept = students.stream()
.collect(Collectors.groupingBy(Student::dept, TreeMap::new,
Collectors.averagingDouble(Student::cgpa)));
avgByDept.forEach((d, a) -> System.out.printf("%s %.2f%n", d, a));
List<String> top = students.stream()
.filter(s -> s.cgpa() >= 3.5)
.sorted((a, b) -> Double.compare(b.cgpa(), a.cgpa()))
.map(Student::name)
.limit(2)
.toList();
System.out.println("Top two: " + top);
Map<Boolean, List<String>> passFail = students.stream()
.collect(Collectors.partitioningBy(s -> s.cgpa() >= 3.0,
Collectors.mapping(Student::name, Collectors.toList())));
System.out.println(passFail);
}
}
Output
{BBA=1, CSE=3, EEE=2}
BBA 3.10
CSE 3.81
EEE 3.20
Top two: [Tania, Nusrat]
{false=[Rafi], true=[Nusrat, Arif, Tania, Imran, Mitu]}
groupingBy(Student::dept, ...)splits the stream into groups by department, much like SQL’s GROUP BY. The second argument (TreeMap::new) chooses a sorted map, and the third (counting()oraveragingDouble(...)) summarises each group.- The “top two” pipeline filters, sorts by CGPA descending, maps to names and stops after two with
limit. partitioningByalways produces exactly two groups,falseandtrue.mappingkeeps only the names in each group.
Common Operations
| Operation | Kind | Purpose |
|---|---|---|
filter(pred) | Intermediate | Keep matching elements |
map(fn) | Intermediate | Transform each element |
flatMap(fn) | Intermediate | Flatten nested collections into one stream |
sorted(), distinct(), limit(n), skip(n) | Intermediate | Order, deduplicate, slice |
collect(...), toList() | Terminal | Gather results |
count(), sum(), min, max | Terminal | Single summary value |
reduce(identity, op) | Terminal | Combine all elements into one |
forEach(action) | Terminal | Perform an action for each element |
Common Mistakes
- Reusing a stream: a stream can be consumed only once; a second terminal call throws
IllegalStateException. - Forgetting the terminal operation, so the pipeline never runs.
- Calling
get()on an empty Optional; preferorElseororElseThrow. - Changing outside variables inside
maporfilter; keep stream steps free of side effects.
Practice Exercises
Exercise 1. From a list of words, produce a list of their lengths for words longer than three letters.
Show answer
List<Integer> lengths = words.stream()
.filter(w -> w.length() > 3)
.map(String::length)
.toList();
Exercise 2. Compute the product of the numbers 1 to 5 using reduce.
Show answer
int product = IntStream.rangeClosed(1, 5).reduce(1, (a, b) -> a * b);
System.out.println(product); // 120
Frequently Asked Questions
Are streams faster than loops?
Not usually. A plain loop is often slightly faster. Streams win on readability, and parallelStream() can help for large, CPU-heavy work, though it adds overhead for small lists.
What is the difference between map and flatMap?
map turns each element into exactly one new element. flatMap turns each element into a stream of zero or more elements and merges them, for example turning a list of sentences into a stream of words.
Summary
- A stream pipeline is source, then lazy intermediate steps, then one terminal step.
filter,map,sortedandlimitcover most transformations.Collectors.groupingByandpartitioningBysummarise data like SQL.- Streams are single-use and leave the source collection unchanged.
Next: Java File Handling.
