How to iterate the contents of a collection using forEach() in Java?


Lambda expression is the anonymous representation of a function descriptor of a functional interface. As we know that all collection interfaces like List, Set and Queue use an Iterable as their super interface. Since Java 8, an Iterable interface introduces a new method called forEach(). This method performs an action on the contents of Iterable in the order elements that occur when iterating until all elements have processed.

Syntax

void forEach(Consumer<? Super T> action)

In the below program, we can iterate the contents of a list using the forEach() method and print the contents by using lambda expression and static method reference.

Example

import java.util.*;
import java.util.function.*;

public class LambdaMethodRefIterationTest {
   public static void main(String[] args) {
      List<String> countries = Arrays.asList("India", "Australia", "England", "Newzealand", "Scotland");

      System.out.println("==== Iterating by passing Lambda Expression ====");
      countries.forEach(s -> System.out.println(s));

      System.out.println("
==== Iterating by passing Static Method Reference ====");       countries.forEach(System.out::println);       System.out.println("
==== Iterating by passing Static Method Reference ====");       countries.forEach(Country::countWord);    } } class Country {    static void countWord(String s) {       System.out.println(s.length());    } }

Output

==== Iterating by passing Lambda Expression ====
India
Australia
England
Newzealand
Scotland

==== Iterating by passing Static Method Reference ====
India
Australia
England
Newzealand
Scotland

==== Iterating by passing Static Method Reference ====
5
9
7
10
8

Updated on: 13-Jul-2020

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements