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

Java 8Object Oriented ProgrammingProgramming

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("\n==== Iterating by passing Static Method Reference ====");
      countries.forEach(System.out::println);

      System.out.println("\n==== 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
raja
Published on 03-Jan-2020 10:57:16
Advertisements