Sobes.tech
Junior — Middle

How does the map method in Stream API work and how is it used to transform stream elements?

sobes.tech AI

Answer from AI

The map method in Java Stream API is used to transform each element of the stream into another element by applying a given function. It returns a new stream consisting of the results of applying the function to the elements of the original stream.

Example usage:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MapExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Anna", "Bob", "Charlie");

        // Transform the list of names into a list of their lengths
        List<Integer> lengths = names.stream()
            .map(name -> name.length())
            .collect(Collectors.toList());

        System.out.println(lengths); // Outputs: [4, 3, 7]
    }
}

Here, map takes each element name from the stream and transforms it into its length name.length(). This allows for easy and efficient data transformation within a stream.

How does the map method in Stream API work and how is… - sobes.tech