Sobes.tech
Junior — Middle

What does the forEach method return when used on a collection?

sobes.tech AI

Answer from AI

The forEach method in Java is used to iterate over elements of a collection and perform a specified action for each element. It takes a Consumer<T> object as an argument, which defines the operation to be applied.

It is important to note that forEach does not return a value — its return type is void. It is only for side effects, such as printing, modifying external variables, etc.

Example usage:

List<String> list = Arrays.asList("a", "b", "c");
list.forEach(item -> System.out.println(item));

Here, forEach simply prints each element but does not return any result.

What does the forEach method return when used on a… - sobes.tech