Java

Stream Basics — filter / map / collect

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
The fluent pipeline for transforming collections. `filter` keeps matching elements, `map` transforms each one, `collect(toList())` materializes the result.
Java
Raw
import java.util.*;
import java.util.stream.*;

class Demo {
    record User(int id, String name, int age) {}

    void example() {
        var users = List.of(
            new User(1, "Alice", 30),
            new User(2, "Bob",   17),
            new User(3, "Cara",  25),
            new User(4, "Dave",  40)
        );

        // Adult user names, uppercase
        List<String> adults = users.stream()
            .filter(u -> u.age() >= 18)
            .map(u -> u.name().toUpperCase())
            .toList();                                 // Java 16+ shorter than collect
        System.out.println(adults);                    // [ALICE, CARA, DAVE]

        // Sum of ages
        int totalAge = users.stream()
            .mapToInt(User::age)                       // unbox to IntStream
            .sum();
        System.out.println(totalAge);                  // 112

        // Average
        OptionalDouble avgAge = users.stream()
            .mapToInt(User::age)
            .average();
        avgAge.ifPresent(a -> System.out.printf("%.1f%n", a));
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.