Sobes.tech
Junior

What functional interface do we work with in the map() method?

sobes.tech AI

Answer from AI

In the map() method of Java streams, we work with the functional interface java.util.function.Function.

// Example of using Function in the map() method
import java.util.List;
import java.util.stream.Collectors;

List<String> words = List.of("hello", "world");

// Function<String, Integer> converts String to Integer
List<Integer> lengths = words.stream()
                             .map(s -> s.length()) // Lambda expression implements Function<String, Integer>
                             .collect(Collectors.toList());

// Another way using method reference
List<Integer> lengthsMethodRef = words.stream()
                                      .map(String::length) // Method reference also implements Function<String, Integer>
                                      .collect(Collectors.toList());

The Function<T, R> interface takes one argument of type T and returns a result of type R. In the context of map(), T is the type of the input stream elements, and R is the type of the output stream elements.

What functional interface do we work with in the… - sobes.tech