Java 8 - forEach() method example

Posted on December 22, 2016


The forEach() method is introduced in JavaSE 8. It processes each elements of the Map or List or Set until all elements have been processed or the action throws an exception.

Map + forEach() example

Iterating map using for-each loop.

for (Entry<String, String> entry : days.entrySet()) {
   System.out.println(entry.getKey() + ":" + entry.getValue());
}

Iterating map using forEach() method.

days.forEach((key, value) -> {
   System.out.println(key + ":" + value);
});

Complete example

ForEachMapExample.java

package com.boraji.tutorial;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author imssbora
 */
public class ForEachMapExample {
   public static void main(String[] args) {
      Map<String, String> days = new HashMap<>();
      days.put("1", "SUN");
      days.put("2", "MON");
      days.put("3", "TUE");

      // Normal method
      System.out.println("Iterating map using entry set");
      for (Entry<String, String> entry : days.entrySet()) {
         System.out.println(entry.getKey() + ":" + entry.getValue());
      }

      // Iterating using forEach
      System.out.println("\nIterating map using forEach method");
      days.forEach((key, value) -> {
         System.out.println(key + ":" + value);
      });
   }
}

Output

Iterating map using entry set
1:SUN
2:MON
3:TUE

Iterating map using forEach method
1:SUN
2:MON
3:TUE

 

List + forEach() example

Iterating list using for-each loop.

for (String l : languages) {
   System.out.println(l);
}

Iterating list using forEach() method.

languages.forEach((l)->{System.out.println(l);});

Complete example

ForEachListExample.java

package com.boraji.tutorial;

import java.util.ArrayList;
import java.util.List;

/**
 * @author imssbora
 */
public class ForEachListExample {
   public static void main(String[] args) {
      List<String> languages= new ArrayList<>();
      languages.add("Java");
      languages.add("C#");
      languages.add("Php");
      languages.add("JavaScript");

      //Normal method
      System.out.println("Iterating list using for-each loop");
      for (String l : languages) {
         System.out.println(l);
      }
      
      //Using forEach method
      System.out.println("\nIterating list using forEach method");
      languages.forEach((l)->{System.out.println(l);});
   }
}

Output

Iterating list using for-each loop
Java
C#
Php
JavaScript

Iterating list using forEach method
Java
C#
Php
JavaScript