Java 8 forEach() List Example

Java ArrayList Examples


Array Methods with Examples


Java 8 provides a new method forEach() to iterate the elements. It is defined in the Iterable and Stream interface.

It is a default method defined in the Iterable interface. Collection classes that extend the Iterable interface can use the forEach() loop to iterate elements.

Normal for loop with List

Let's use normal for-loop to loop a List.
public static void forEachWithList() {

    final List < Person > items = new ArrayList < > ();
    items.add(new Person(100, "Ramesh"));
    items.add(new Person(100, "A"));
    items.add(new Person(100, "B"));
    items.add(new Person(100, "C"));
    items.add(new Person(100, "D"));

    for (final Person item: items) {
        System.out.println(item.getName());
    }
}

forEach() method with List Example

In Java 8, you can loop a List with forEach + lambda expression or method reference. Please refer to the comments in the above example are self-descriptive.
public static void forEachWithList() {

    final List < Person > items = new ArrayList < > ();
    items.add(new Person(100, "Ramesh"));
    items.add(new Person(100, "A"));
    items.add(new Person(100, "B"));
    items.add(new Person(100, "C"));
    items.add(new Person(100, "D"));

    //lambda
    items.forEach(item - > System.out.println(item.getName()));

    //Output : C
    items.forEach(item - > {
        if ("C".equals(item)) {
            System.out.println(item);
        }
    });

    //method reference
    //Output : A,B,C,D,E
    items.forEach(System.out::println);

    //Stream and filter
    //Output : B
    items.stream()
        .filter(s - > s.getName().equals("Ramesh"))
        .forEach(System.out::println);
}

Comments