Reading history

Java Streams API: filter, map, collect and groupingBy

5 min read 0 views

Learn the Java Streams API: pipelines, filter, map, sorted, limit, numeric streams, anyMatch, and Collectors groupingBy, partitioningBy and joining.

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, distinct and limit
  • Numeric streams: sum, average, max
  • Matching with anyMatch and allMatch
  • 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.
  • mapToInt converts to an IntStream, which has sum() and average(). average() returns an OptionalDouble because an empty stream has no average; orElse(0) supplies a fallback.
  • distinct() removes duplicates and sorted() sorts. toList() (Java 16+) collects into an unmodifiable list.
  • anyMatch and allMatch stop as soon as the answer is known.
  • Collectors.joining builds one string from many.
  • Streams do not change the source list; nums is 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() or averagingDouble(...)) summarises each group.
  • The “top two” pipeline filters, sorts by CGPA descending, maps to names and stops after two with limit.
  • partitioningBy always produces exactly two groups, false and true. mapping keeps only the names in each group.

Common Operations

OperationKindPurpose
filter(pred)IntermediateKeep matching elements
map(fn)IntermediateTransform each element
flatMap(fn)IntermediateFlatten nested collections into one stream
sorted(), distinct(), limit(n), skip(n)IntermediateOrder, deduplicate, slice
collect(...), toList()TerminalGather results
count(), sum(), min, maxTerminalSingle summary value
reduce(identity, op)TerminalCombine all elements into one
forEach(action)TerminalPerform an action for each element

Common Mistakes

  1. Reusing a stream: a stream can be consumed only once; a second terminal call throws IllegalStateException.
  2. Forgetting the terminal operation, so the pipeline never runs.
  3. Calling get() on an empty Optional; prefer orElse or orElseThrow.
  4. Changing outside variables inside map or filter; 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, sorted and limit cover most transformations.
  • Collectors.groupingBy and partitioningBy summarise data like SQL.
  • Streams are single-use and leave the source collection unchanged.

Next: Java File Handling.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *