Java
Beginner
1 min read
Stream filter, map, and collect
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);
}
}