Java 8 Iterable.forEach() vs foreach loop

In Java 8, the Iterable.forEach() method is a default method that allows you to iterate over the elements of an Iterable (such as a List or Set) and perform a specific action on each element.

Here is an example of how to use the forEach() method to print the elements of a list:

List<String> list = Arrays.asList("A", "B", "C");
list.forEach(System.out::println);

This will print the elements of the list to the console:

A
B
C

The forEach() method is similar to the for-each loop, but it is more concise and can be easier to read.

Here is an example of how to use a for-each loop to print the elements of a list:

List<String> list = Arrays.asList("A", "B", "C");
for (String s : list) {
  System.out.println(s);
}

This will also print the elements of the list to the console.

Both the forEach() method and the for-each loop are useful for iterating over the elements of a collection and performing a specific action on each element. However, the forEach() method can be more concise and easier to read in some cases.