Resources

Java

Java Streams

Last updated 5 July 2026

  • java
  • streams
  • collections

Also known as: java stream api, stream filter map, java collect, stream collectors

Filter + map + collect

List<String> names = people.stream()
    .filter(p -> p.getAge() >= 18)
    .map(Person::getName)
    .collect(Collectors.toList());

Common terminal operations

long count = people.stream().filter(p -> p.getAge() >= 18).count();

boolean anyAdults = people.stream().anyMatch(p -> p.getAge() >= 18);

Optional<Person> oldest = people.stream()
    .max(Comparator.comparingInt(Person::getAge));

Grouping

Map<Boolean, List<Person>> byAdult = people.stream()
    .collect(Collectors.partitioningBy(p -> p.getAge() >= 18));

Map<String, List<Person>> byCity = people.stream()
    .collect(Collectors.groupingBy(Person::getCity));

Joining strings

String csv = people.stream()
    .map(Person::getName)
    .collect(Collectors.joining(", "));

Streams are lazy

Nothing runs until a terminal operation (collect, count, forEach, etc.) is called — filter and map just build a pipeline.

Stream<String> pipeline = names.stream().filter(n -> n.startsWith("A")); // nothing happens yet
pipeline.forEach(System.out::println); // now it runs

Note

A stream can only be consumed once — calling a terminal operation twice on the same stream throws IllegalStateException.