Which method in the Stream API is used to convert elements to another type?

Java MCQ: Which method in the Stream API is used to convert elements to another type?

a) filter()
b) collect()
c) map()
d) reduce()

Answer:

c) map()

Explanation:

The map() method in the Stream API is used to convert elements of a stream to another type. It applies the provided function to each element in the stream, producing a new stream of the results.

Here’s an example of using map() to convert a list of strings to a list of their lengths:

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

public class StreamMapExample {
    public static void main(String[] args) {
        List<String> names = List.of("John", "Jane", "Jack", "Doe");
        List<Integer> nameLengths = names.stream()
                                          .map(String::length)
                                          .collect(Collectors.toList());

        nameLengths.forEach(System.out::println);
    }
}

In this example, the map() method converts each string in the names list to its length, resulting in a stream of integers. These integers are then collected into a list and printed.

The map() method is a powerful tool in the Stream API, enabling developers to transform data within a stream pipeline.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top