Which method in the Stream API is used to filter elements based on a predicate?

Java MCQ: Which method in the Stream API is used to filter elements based on a predicate?

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

Answer:

b) filter()

Explanation:

The filter() method in the Stream API is used to filter elements based on a predicate. A predicate is a functional interface that represents a boolean-valued function, often used to test conditions on elements in a stream.

Here’s an example of using filter():

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

public class StreamFilterExample {
    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"))
                                          .collect(Collectors.toList());

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

In this example, the filter() method is used to filter out names that do not start with “J”. The result is a list containing only the names that match the predicate, and these names are then printed.

The filter() method is a key part of the Stream API, allowing for the creation of more concise and readable code when processing collections of data.

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