Junior — Middle
What value does the map method return for objects of type Stream in Java?
sobes.tech AI
Answer from AI
The map method on Stream objects in Java returns a new stream (Stream) whose elements are obtained by applying a given function to the elements of the original stream. This is an intermediate operation that does not modify the original stream but creates a new, transformed one.
Example:
List<String> names = List.of("Anna", "Bob", "Cathy");
List<Integer> lengths = names.stream()
.map(String::length) // transform each name into its length
.collect(Collectors.toList());
System.out.println(lengths); // Outputs: [4, 3, 5]
Thus, map allows transforming data in a stream by applying a function to each element.