SyntaxStudy
Sign Up
Java Stream filter, map, and collect
Java Beginner 1 min read

Stream filter, map, and collect

The Java Stream API, introduced in Java 8, provides a functional-style approach to processing collections of data. A stream is not a data structure — it is a pipeline of operations applied to a source (a collection, array, or I/O channel). Streams are lazy: intermediate operations like filter and map are not executed until a terminal operation is called. This allows the JVM to optimise the pipeline and avoid unnecessary computations. filter() takes a Predicate and retains only the elements for which the predicate returns true. map() takes a Function and transforms each element into a new value, possibly of a different type. These two operations are the backbone of most stream pipelines. Operations can be chained fluently, making the intent of the code clear and readable compared to equivalent imperative loops. collect() is the most common terminal operation. It gathers the stream elements into a container using a Collector. The Collectors utility class provides factory methods for the most common collectors: toList(), toSet(), toMap(), joining() for concatenating strings, and groupingBy() for partitioning elements into a map of lists. The result of collect() materialises the stream pipeline into a concrete data structure.
Example
import java.util.*;
import java.util.stream.*;

public class StreamBasicsDemo {
    record Person(String name, int age, String city) {}

    public static void main(String[] args) {
        List<Person> people = List.of(
            new Person("Alice",  28, "London"),
            new Person("Bob",    35, "Paris"),
            new Person("Carol",  22, "London"),
            new Person("Dave",   31, "Berlin"),
            new Person("Eve",    28, "Paris")
        );

        // filter + map + collect to List
        List<String> londonNames = people.stream()
            .filter(p -> p.city().equals("London"))
            .map(Person::name)
            .collect(Collectors.toList());
        System.out.println("London residents: " + londonNames);

        // filter + map + sorted + collect
        List<String> youngSorted = people.stream()
            .filter(p -> p.age() < 30)
            .map(p -> p.name() + " (" + p.age() + ")")
            .sorted()
            .collect(Collectors.toList());
        System.out.println("Under 30 sorted:  " + youngSorted);

        // Collectors.joining
        String nameList = people.stream()
            .map(Person::name)
            .collect(Collectors.joining(", ", "[", "]"));
        System.out.println("Name list: " + nameList);

        // Collectors.groupingBy
        Map<String, List<String>> byCity = people.stream()
            .collect(Collectors.groupingBy(
                Person::city,
                Collectors.mapping(Person::name, Collectors.toList())
            ));
        System.out.println("By city: " + byCity);
    }
}