map
- Java course
- Intermediate
- Lesson 108/116
- 5 min
Learn to transform elements with map.
Transforming with map
map(Function) transforms each element into a new value and returns a new Stream. Function<T, R> is a functional interface with a single apply(T) method; T is the input type, R the output type.
Example: names.stream().map(s -> s.length()) turns each String into its length; the result is a Stream<Integer>. map is a transformation; it does not change the element count. The stream continues even if the type changes.
mapToInt and primitive specialization
For primitive results use mapToInt, mapToLong, mapToDouble. They return IntStream, LongStream, DoubleStream; these allow primitive operations like sum() and average().
For example names.stream().mapToInt(s -> s.length()).sum() gives the total length of names. This is more concise than map(s -> s.length()).reduce(0, (a, b) -> a + b). The average() method returns Optional, safely read with .orElse(0.0).
Practice Sum name lengths
Declare List<String> names = new ArrayList<>();; add "Ayşe" and "Alex". Compute the total of name lengths with int sum = names.stream().mapToInt(s -> s.length()).sum();. Print it with System.out.println(sum);.
Starter code
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Declare List<String>, add two names, sum lengths with mapToInt+sum, print
}
}Sample solution
import java.util.List;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ayşe");
names.add("Alex");
int sum = names.stream().mapToInt(s -> s.length()).sum();
System.out.println(sum);
}
}Expected output
8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the map concepts
| Term | Meaning |
|---|---|
map(...) |
Transforms each element |
Function<T, R> |
Transform function |
apply(T) |
R-typed result |
s -> s.length() |
Lambda Function |
2 Complete the map call
names.stream().____(s -> s.length())
names.stream().map(s -> s.length())
Explanation: The map method expects a Function.
3 What does names.stream().map(s -> s.length()) return?
- Stream<String>
- Stream<Integer> Correct answer
- long
- List<Integer>
Explanation: map turns each String into an Integer; the result is a Stream<Integer>.