map

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • map(Function<T, R>) is an intermediate operation.
  • It transforms every element in the stream from type T to type R by applying the provided function.
  • It is a 1-to-1 mapping; the resulting stream will have the exact same number of elements as the input stream.

Concept

map is used to convert data or extract specific fields.
If you have a Stream<Employee> and you only need their salaries, you can use .map(Employee::getSalary) to transform the stream into a Stream<Double>.

Because it accepts a Function interface, you can pass any lambda expression that takes an input and returns an output.

Examples

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MapExample {
    public static void main(String[] args) {
        
        List<String> words = Arrays.asList("java", "streams", "are", "cool");
        
        // 1. Transforming type (String -> Integer)
        List<Integer> lengths = words.stream()
            .map(String::length) // or str -> str.length()
            .collect(Collectors.toList());
            
        System.out.println(lengths); // [4, 7, 3, 4]
        
        
        // 2. Modifying data (String -> String)
        List<String> upper = words.stream()
            .map(String::toUpperCase)
            .collect(Collectors.toList());
            
        System.out.println(upper); // [JAVA, STREAMS, ARE, COOL]
    }
}

Interview Questions

Q: What is the difference between map and mapToInt?
A: While map returns a standard Stream<Integer>, mapToInt returns an IntStream (a specialized stream for primitive ints). IntStream avoids the performance overhead of auto-boxing primitives into objects. Furthermore, IntStream provides specialized mathematical terminal operations that a standard Stream does not have, such as .sum() and .average().

Q: Can map filter out elements?
A: No. map is strictly for transformation, and it is a 1-to-1 mapping. If the input stream has 10 items, the output stream will have 10 items. If your mapping function returns null for some elements, those nulls will remain in the stream. To remove elements, you must use filter().