javabeginner

Java Streams — Filter, Map, Collect

Process collections with Java Streams: filter, map, flatMap, reduce, and collect to lists or maps.

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

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

    public static void main(String[] args) {
        List<Person> people = List.of(
            new Person("Alice", 30, "NYC"),
            new Person("Bob", 25, "LA"),
            new Person("Charlie", 35, "NYC"),
            new Person("Diana", 28, "LA")
        );

        // Filter + Map + Collect
        List<String> nycNames = people.stream()
            .filter(p -> p.city().equals("NYC"))
            .map(Person::name)
            .sorted()
            .collect(Collectors.toList());
        System.out.println(nycNames); // [Alice, Charlie]

        // Average age
        double avgAge = people.stream()
            .mapToInt(Person::age)
            .average()
            .orElse(0.0);
        System.out.printf("Average age: %.1f%n", avgAge);

        // Group by city
        Map<String, List<Person>> byCity = people.stream()
            .collect(Collectors.groupingBy(Person::city));

        // Count per city
        Map<String, Long> countByCity = people.stream()
            .collect(Collectors.groupingBy(Person::city, Collectors.counting()));

        // Partition: age >= 30 vs < 30
        Map<Boolean, List<Person>> partitioned = people.stream()
            .collect(Collectors.partitioningBy(p -> p.age() >= 30));

        // Join names
        String names = people.stream()
            .map(Person::name)
            .collect(Collectors.joining(", "));
        System.out.println(names); // Alice, Bob, Charlie, Diana
    }
}

Use Cases

  • Transforming and filtering collections
  • Aggregating data with grouping and partitioning
  • Replacing verbose loops with declarative pipelines

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.