Java MCQ: Which Stream API method is used to execute a terminal operation that does not produce a result but applies an action to each element?
Answer:
Explanation:
The forEach()
method in the Stream API is used to execute a terminal operation that does not produce a result but applies an action to each element in the stream. This method takes a Consumer
(a functional interface) as an argument and performs the specified action on each element of the stream.
Here’s an example of using forEach()
:
import java.util.List;
public class StreamForEachExample {
public static void main(String[] args) {
List<String> names = List.of("John", "Jane", "Jack", "Doe");
names.stream().forEach(System.out::println);
}
}
In this example, forEach()
is used to print each name in the names
list to the console. The System.out::println
method reference is passed as a Consumer
, which is applied to each element of the stream.
forEach()
is commonly used when you need to perform side effects with each element of the stream, such as printing or updating a database. It is a terminal operation, meaning that after forEach()
is called, the stream is considered consumed and cannot be reused.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html