Sobes.tech
Junior

Ar kuru funkcionālo interfeisu mēs strādājam map() metodē?

sobes.tech AI

Atbilde no AI

Java straumju map() metodes darbā mēs strādājam ar funkcionālo interfeisu java.util.function.Function.

// Piemērs, kā izmantot Function `map()` metodē
import java.util.List;
import java.util.stream.Collectors;

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

// Function<String, Integer> pārvērš String uz Integer
List<Integer> lengths = words.stream()
                             .map(s -> s.length()) // Lambda izteiksme realizē Function<String, Integer>
                             .collect(Collectors.toList());

// Cits veids, izmantojot metodes atsauci
List<Integer> lengthsMethodRef = words.stream()
                                      .map(String::length) // Metodes atsauce arī realizē Function<String, Integer>
                                      .collect(Collectors.toList());

Function<T, R> interfeiss pieņem vienu argumentu T tipā un atgriež rezultātu R tipā. map() kontekstā, T ir ieejas straumes elementu tips, bet R – izejas straumes elementu tips.