Skip Top Navigation Bar

Iterating Over ArrayList with Lambda and forEach

The ArrayList class has a forEach method. This method takes a Consumer object as a parameter. Consumer is an interface that has an accept method that needs to be implemented. The accept method performs an operation on the given argument.

The following example passes the implementation of the method accept as an argument to the forEach method. For example, names is an ArrayList of String values:

Try it in the Java Playground

  1. Predict the output of the code then test your prediction by running it in the Java Playground.
  2. Edit the length requirement to greater than 3 and see how this changes the output.