You are here
Home >

Which of these does Stream.forEach() operates on?

A) Function
B) Consumer
C) Producer
D) Predicate

Ans. B) Consumer 

Explanation

The stream.forEach() method in Java’s Stream API operates on a Consumer. Here’s a detailed explanation:

Stream API: Java introduced the Stream API in Java 8, which provides a functional approach to processing sequences of elements. Streams can be created from various data sources, including collections, arrays, and I/O channels.

forEach() Method: The forEach() method is a terminal operation in the Stream API that performs an action for each element of the stream. This method takes a Consumer as an argument.

Consumer: A Consumer is a functional interface defined in the java.util.function package. It represents an operation that accepts a single input argument and returns no result. The functional method of Consumer is accept(T t). When we use stream.forEach(), we provide a Consumer implementation, typically as a lambda expression or method reference, which specifies the action to be performed on each element.

Example:

Here’s a simple example demonstrating how forEach() operates on a Consumer:

import java.util.Arrays;
import java.util.List;

public class StreamForEachExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Core Java", "Spring", "Hibernate");

        // Using forEach with a lambda expression
        names.stream().forEach(name -> System.out.println(name));

        // Using forEach with a method reference
        names.stream().forEach(System.out::println);
    }
}

In this example:

names.stream() creates a stream from the list names.

forEach(name -> System.out.println(name)) uses a lambda expression, which is a Consumer that prints each name.

forEach(System.out::println) uses a method reference, which is also a Consumer.

Thus, B) Consumer the correct answer.

In order to practice a series of MCQs on Java & related technologies, kindly visit Java MCQs/Quizzes section.


Top