How to transform every element of a list
Short answer
map() applies a function to every element and returns a stream of results:
void main() {
var names = List.of("anna", "oleg");
var upper = names.stream().map(String::toUpperCase).toList();
IO.println(upper);
}Output:
[ANNA, OLEG]Extracting a field
A common case is getting a list of values of one field:
record User(String name, String email) {}
void main() {
var users = List.of(new User("Anna", "anna@site.com"), new User("Oleg", "oleg@site.com"));
IO.println(users.stream().map(User::email).toList());
}Output:
[anna@site.com, oleg@site.com]Numbers
mapToInt() gives a number stream with sum(), max() and average():
void main() {
var words = List.of("java", "is", "fun");
IO.println(words.stream().mapToInt(String::length).sum());
}Output:
9Changing in place
replaceAll() replaces every element of a modifiable list with the function's result:
void main() {
var prices = new ArrayList<>(List.of(10, 20, 30));
prices.replaceAll(p -> p * 2);
IO.println(prices);
}Output:
[20, 40, 60]Common mistake
Using forEach() to fill another list. It works, but map() with toList() is shorter and needs no mutable list outside:
void main() {
var names = List.of("anna", "oleg");
var result = new ArrayList<String>();
names.forEach(n -> result.add(n.toUpperCase()));
IO.println(result);
IO.println(names.stream().map(String::toUpperCase).toList());
}Output:
[ANNA, OLEG]
[ANNA, OLEG]Functions used in this recipe
- Stream.map() — Transforms every element of a stream.
- Stream.toList() — Gathers stream elements into an unmodifiable list.
- List.replaceAll() — Replaces every list element with the result of a function.