The forEach()
method is a method of the Iterable
interface in Java that allows you to iterate over the elements in a collection and perform an action on each element. The forEach()
method takes a single argument, a Consumer
object, which is a functional interface that represents an operation that accepts a single input argument and returns no result.
Here's an example of how to use the forEach()
method to iterate over a list and print each element to the console:
import java.util.List; public class Main { public static void main(String[] args) { List<String> list = List.of("a", "b", "c"); // Iterate over the elements in the list and print each element to the console list.forEach(e -> System.out.println(e)); } }
This code creates a list of strings and then uses the forEach()
method to iterate over the elements in the list. The forEach()
method takes a Consumer
object as an argument, in this case a lambda expression that prints the element to the console.
You can use the forEach()
method to iterate over any collection that implements the Iterable
interface, such as a List
, a Set
, or a Queue
.
You can find more information about the forEach()
method and the Iterable
interface in the Java documentation.