Java Streams for Beginners: filter, map, reduce and collect

admin5 min read
In this tutorial
  1. Our example data
  2. Loop versus stream
  3. How a stream pipeline works
  4. filter: keep what matches
  5. map: transform each element
  6. sorted and limit
  7. reduce: combine into one value
  8. Finding elements and Optional
  9. collect and groupingBy
  10. Pitfalls to avoid
  11. Practice
  12. Summary

Before Java 8, processing a list meant writing loops, temporary lists and counters. Streams let you describe what you want (“the names of students who passed, sorted”) instead of how to loop through everything. The result is shorter code that reads almost like a sentence.

This tutorial introduces streams from scratch using one realistic data set.

Our example data

record Order(String customer, String city, double amount, boolean paid) { }

List<Order> orders = List.of(
    new Order("Ada", "Lagos", 25_000, true),
    new Order("Chidi", "Abuja", 8_500, false),
    new Order("Fatima", "Kano", 42_000, true),
    new Order("Tunde", "Lagos", 15_750, true),
    new Order("Bola", "Ibadan", 5_200, true),
    new Order("Emeka", "Abuja", 31_000, true)
);

Loop versus stream

Goal: the names of customers with paid orders over NGN 10,000, in alphabetical order.

With a loop:

List<String> names = new ArrayList<>();
for (Order o : orders) {
    if (o.paid() && o.amount() > 10_000) {
        names.add(o.customer());
    }
}
Collections.sort(names);

With a stream:

List<String> names = orders.stream()
        .filter(o -> o.paid() && o.amount() > 10_000)
        .map(Order::customer)
        .sorted()
        .toList();
// [Ada, Emeka, Fatima, Tunde]

Each line does one job, and the pipeline reads from top to bottom.

How a stream pipeline works

Every stream has three parts:

  1. A source: list.stream(), Arrays.stream(array), Stream.of(...), IntStream.range(0, 10).
  2. Zero or more intermediate operations: filter, map, sorted, distinct, limit. Each returns a new stream.
  3. One terminal operation: toList, collect, forEach, count, reduce, findFirst. This produces the result.

Streams are lazy: nothing happens until the terminal operation runs. They also do not modify the source list.

filter: keep what matches

long unpaid = orders.stream()
        .filter(o -> !o.paid())
        .count();   // 1

filter takes a Predicate, a function that returns true for elements you want to keep.

map: transform each element

List<String> cities = orders.stream()
        .map(Order::city)
        .distinct()
        .toList();   // [Lagos, Abuja, Kano, Ibadan]

Order::city is a method reference, shorthand for o -> o.city().

For numbers, use the primitive versions (mapToDouble, mapToInt) to avoid boxing and to get handy methods like sum and average:

double revenue = orders.stream()
        .filter(Order::paid)
        .mapToDouble(Order::amount)
        .sum();   // 118950.0

sorted and limit

List<Order> topThree = orders.stream()
        .sorted(Comparator.comparingDouble(Order::amount).reversed())
        .limit(3)
        .toList();
// Fatima 42000, Emeka 31000, Ada 25000

reduce: combine into one value

reduce folds all elements into a single result:

double total = orders.stream()
        .map(Order::amount)
        .reduce(0.0, Double::sum);

For sums, mapToDouble(...).sum() is clearer. Use reduce for custom combinations.

Finding elements and Optional

findFirst, max and min might not find anything, so they return an Optional:

Optional<Order> biggest = orders.stream()
        .max(Comparator.comparingDouble(Order::amount));

biggest.ifPresent(o -> System.out.println("Biggest: " + o.customer())); // Fatima

String firstAbuja = orders.stream()
        .filter(o -> o.city().equals("Abuja"))
        .map(Order::customer)
        .findFirst()
        .orElse("none");   // Chidi

anyMatch, allMatch and noneMatch answer yes/no questions and stop early:

boolean anyLarge = orders.stream().anyMatch(o -> o.amount() > 40_000); // true

collect and groupingBy

Collectors turn a stream into maps, joined strings and summaries:

import java.util.*;
import java.util.stream.Collectors;

public class StreamsDemo {
    record Order(String customer, String city, double amount, boolean paid) { }

    public static void main(String[] args) {
        List<Order> orders = List.of(
            new Order("Ada", "Lagos", 25_000, true),
            new Order("Chidi", "Abuja", 8_500, false),
            new Order("Fatima", "Kano", 42_000, true),
            new Order("Tunde", "Lagos", 15_750, true),
            new Order("Bola", "Ibadan", 5_200, true),
            new Order("Emeka", "Abuja", 31_000, true)
        );

        // Orders per city
        Map<String, Long> countByCity = orders.stream()
                .collect(Collectors.groupingBy(Order::city, TreeMap::new, Collectors.counting()));
        System.out.println(countByCity); // {Abuja=2, Ibadan=1, Kano=1, Lagos=2}

        // Total paid revenue per city
        Map<String, Double> revenueByCity = orders.stream()
                .filter(Order::paid)
                .collect(Collectors.groupingBy(Order::city, TreeMap::new,
                        Collectors.summingDouble(Order::amount)));
        System.out.println(revenueByCity); // {Abuja=31000.0, Ibadan=5200.0, Kano=42000.0, Lagos=40750.0}

        // Paid vs unpaid
        Map<Boolean, List<String>> byStatus = orders.stream()
                .collect(Collectors.partitioningBy(Order::paid,
                        Collectors.mapping(Order::customer, Collectors.toList())));
        System.out.println(byStatus.get(false)); // [Chidi]

        // One comma-separated string
        String customers = orders.stream()
                .map(Order::customer)
                .collect(Collectors.joining(", "));
        System.out.println(customers); // Ada, Chidi, Fatima, Tunde, Bola, Emeka

        // Statistics in one pass
        DoubleSummaryStatistics stats = orders.stream()
                .mapToDouble(Order::amount)
                .summaryStatistics();
        System.out.printf("min=%.0f max=%.0f avg=%.2f%n", stats.getMin(), stats.getMax(), stats.getAverage());
        // min=5200 max=42000 avg=21241.67
    }
}

We pass TreeMap::new so the output is sorted by city. A plain groupingBy returns a HashMap with no guaranteed order.

Pitfalls to avoid

  • Streams can only be used once. Calling a second terminal operation on the same stream throws IllegalStateException. Create a new stream instead.
  • Avoid side effects. Do not add to an outside list inside forEach or map; use collect or toList.
  • toList() returns an unmodifiable list (Java 16+). Use collect(Collectors.toCollection(ArrayList::new)) if you need to change it afterwards.
  • Don’t force everything into a stream. A simple loop with an early break, or code that updates several variables, is often clearer as a loop.
  • Parallel streams are not a free speed-up. parallelStream() only helps for large, CPU-heavy work, and can be slower for small lists.

Practice

Using the orders list:

  1. Find the average amount of paid orders in Lagos.
  2. Produce a list of customer names in upper case, sorted by order amount, highest first.
  3. Build a Map<String, Double> of the largest single order per city.

Summary

  • A stream pipeline is source → intermediate operations → one terminal operation.
  • filter selects, map transforms, sorted orders, limit truncates.
  • collect with groupingBy, partitioningBy and joining builds maps and strings.
  • Methods that might find nothing return Optional; handle it with orElse or ifPresent.
  • Streams are lazy, single-use and work best without side effects.

Ask a question or leave a comment

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