Java program to iterate over arraylist using lambda expression
You can iterate over an ArrayList
using a lambda expression in Java 8 and higher versions. Here's an example:
import java.util.ArrayList; public class ArrayListLambda { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("Apple"); list.add("Banana"); list.add("Cherry"); list.add("Date"); list.forEach((str) -> System.out.println(str)); } }
In the above example, we define an ArrayList
of String
type with four elements. We use the forEach()
method of the ArrayList
class to iterate over the elements of the list using a lambda expression.
Inside the lambda expression, we use the variable str
to represent each element of the list. We then print each element to the console using the System.out.println()
method.
After running the above code, the output would be:
Apple Banana Cherry Date
This program iterates over the ArrayList
and prints each element to the console using a lambda expression. The forEach()
method is a default method introduced in Java 8, which simplifies the iteration process by hiding the implementation details.