Middle+
What does the map method do in streams?
sobes.tech AI
Answer from AI
The map method in Java Stream API is used for transforming elements of a stream. It takes a function that is applied to each element of the original stream, and returns a new stream consisting of the results of that function.
Example:
List<String> names = List.of("Anna", "Bob", "Cathy");
List<Integer> nameLengths = names.stream()
.map(String::length) // transform each name into its length
.collect(Collectors.toList());
System.out.println(nameLengths); // [4, 3, 5]
Thus, map allows transforming data within a stream without modifying the original stream, but creating a new one with transformed elements.