How can we iterate the elements of List and Map using lambda expression in Java?


The lambda expressions are inline code that implements a functional interface without creating an anonymous class. In Java 8, forEach statement can be used along with lambda expression that reduces the looping through a Map to a single statement and also iterates over the elements of a list. The forEach() method defined in an Iterable interface and accepts lambda expression as a parameter.

Example ( List using Lambda Expression)

import java.util.*;

public class ListIterateLambdaTest {
   public static void main(String[] argv) {
      List<String> countryNames = new ArrayList<String>();
      countryNames.add("India");
      countryNames.add("England");
      countryNames.add("Australia");
      countryNames.add("Newzealand");
      countryNames.add("South Africa");

      // Iterating country names through forEach using Lambda Expression
      countryNames.forEach(name -> System.out.println(name));
   }
}

Output

India
England
Australia
Newzealand
South Africa


Example (Map using Lambda Expression)

import java.util.*;

public class MapIterateLambdaTest {
   public static void main(String[] args) {
      Map<String, Integer> ranks = new HashMap<String, Integer>();
      ranks.put("India", 1);
      ranks.put("Australia", 2);
      ranks.put("England", 3);
      ranks.put("Newzealand", 4);
      ranks.put("South Africa", 5);
      // Iterating through      
      forEach using Lambda Expression
      ranks.forEach((k,v) -> System.out.println("Team : " + k + ", Rank : " + v));
   }
}

Output

Team : Newzealand, Rank : 4
Team : England, Rank : 3
Team : South Africa, Rank : 5
Team : Australia, Rank : 2
Team : India, Rank : 1

Updated on: 11-Jul-2020

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements