Sobes.tech
Junior — Middle

Which functional interface is used for the map method in the Stream API?

sobes.tech AI

Answer from AI

The map method in Java's Stream API uses the functional interface Function<T, R>, where:

  • T is the type of the input element of the stream,
  • R is the type of the result after transformation.

The map method accepts an object of type Function<T, R>, which defines how to transform each element of the stream.

Example usage:

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

public class Example {
    public static void main(String[] args) {
        List<String> strings = Arrays.asList("1", "2", "3");
        List<Integer> numbers = strings.stream()
            .map(Integer::parseInt) // Function<String, Integer>
            .collect(Collectors.toList());
        System.out.println(numbers); // [1, 2, 3]
    }
}
Which functional interface is used for the map method… - sobes.tech