Skip to main content
Java 8 (LTS) · Topic 5 of 12

map, filter and collect

Definition​

A stream is a pipeline for data. filter keeps items that match, map changes each item, and collect or toList gathers the result. Nothing runs until that final step.

Example code​

Names of adults, in capitals

import java.util.List;

record Person(String name, int age) { }

class Demo {
public static void main(String[] args) {
List<Person> people = List.of(new Person("Asha", 30), new Person("Ravi", 17), new Person("Meera", 25));

List<String> adults = people.stream()
.filter(p -> p.age() >= 18) // keep adults
.map(p -> p.name().toUpperCase()) // turn each Person into a name
.toList(); // run the pipeline and collect

System.out.println(adults);
}
}

// Output:
// [ASHA, MEERA]

Finished this page? Track your progress (saved only in your browser).