What is the primary use of the Stream API introduced in Java 8?

Java MCQ: What is the primary use of the Stream API introduced in Java 8?

a) To manage files and directories
b) To process collections of data in a functional style
c) To handle exceptions in a new way
d) To create and manage threads

Answer:

b) To process collections of data in a functional style

Explanation:

The Stream API, introduced in Java 8, is primarily used to process collections of data in a functional style. It allows for operations such as filtering, mapping, and reducing data in a concise and expressive manner.

A stream represents a sequence of elements that can be processed in a pipeline of operations. The Stream API provides methods like filter(), map(), reduce(), collect(), and others, which allow developers to perform complex data transformations and aggregations using a functional approach.

Here’s an example of using the Stream API to filter and map a list of strings:

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

public class StreamExample {
    public static void main(String[] args) {
        List<String> names = List.of("John", "Jane", "Jack", "Doe");
        List<String> filteredNames = names.stream()
                                          .filter(name -> name.startsWith("J"))
                                          .map(String::toUpperCase)
                                          .collect(Collectors.toList());

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

In this example, the stream() method is used to create a stream from the names list. The stream is then filtered to include only names that start with “J”, and each name is converted to uppercase using map(). Finally, the results are collected into a list and printed.

The Stream API simplifies data processing in Java, making it more readable and less error-prone, and it is one of the most significant additions to the language in Java 8.

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