Junior — Middle
Can you explain what the map method is in the context of Java's Stream API?
sobes.tech AI
Answer from AI
The map method in Java's Stream API is used to transform elements of a stream from one type to another. It takes a function that is applied to each element of the stream and returns a new stream with the results of that function.
For example, if you have a stream of strings and want to get a stream of their lengths, you can use map:
List<String> words = Arrays.asList("apple", "banana", "cherry");
List<Integer> lengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println(lengths); // Outputs [5, 6, 6]
Thus, map allows for easy and convenient transformation of data in a stream without modifying the original stream.