Sobes.tech
Junior

Z jakim interfejsem funkcyjnym pracujemy w metodzie map()?

sobes.tech AI

Odpowiedź od AI

W metodzie map() strumieni Java pracujemy z interfejsem funkcyjnym java.util.function.Function.

// Przykład użycia Function w metodzie map()
import java.util.List;
import java.util.stream.Collectors;

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

// Function<String, Integer> konwertuje String na Integer
List<Integer> lengths = words.stream()
                             .map(s -> s.length()) // Wyrażenie lambda implementuje Function<String, Integer>
                             .collect(Collectors.toList());

// Inny sposób z użyciem referencji do metody
List<Integer> lengthsMethodRef = words.stream()
                                      .map(String::length) // Referencja do metody również implementuje Function<String, Integer>
                                      .collect(Collectors.toList());

Interfejs Function<T, R> przyjmuje jeden argument typu T i zwraca wynik typu R. W kontekście map(), T to typ elementów wejściowego strumienia, a R to typ elementów wyjściowego strumienia.