Monday, 16 July 2018

Java8: Map: forEach example

'java.util.Map' interface provides 'forEach' method, it is used to perform given action on every entry in the map.

‘forEach’ method is implemented like below.

default void forEach(BiConsumer<? super K, ? super V> action) {
    Objects.requireNonNull(action);
    for (Map.Entry<K, V> entry : entrySet()) {
        K k;
        V v;
        try {
            k = entry.getKey();
            v = entry.getValue();
        } catch(IllegalStateException ise) {
            // this usually means the entry is no longer in the map.
            throw new ConcurrentModificationException(ise);
        }
        action.accept(k, v);
    }
}



As you see the definition of forEach method, it calls 'action.accept' method on every entry of the map.

Example 1: Below statements print each entry of the map
countriesMap.forEach((key, value) -> {
         System.out.println("Country : " + key + ", Capital : " + value);
});

Example 2: Below statements print each entry of the map in upper case
countriesMap.forEach((key, value) -> {
         System.out.println("Country : " + key.toUpperCase() + ", Capital : " + value.toUpperCase());
});
        
Find the below working application.

Test.java

package com.sample.app;

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

public class Test {

 private static Map<String, String> countriesMap = new HashMap<>();

 private static void loadCountriesMap() {
  countriesMap.put("Belgium", "Belmopan");
  countriesMap.put("Cuba", "Havana");
  countriesMap.put("Georgia", "Tbilisi");
  countriesMap.put("Mongolia", "Ulaanbaatar");
  countriesMap.put("Nepal", "Kathmandu");
  countriesMap.put("Poland", "Warsaw");
  countriesMap.put("Sweden", "Stockholm");
 }

 static {
  loadCountriesMap();
 }

 public static void main(String args[]) {
  /* Print countries and their capitals */
  System.out.println("Countries and their capitals in raw form");
  countriesMap.forEach((key, value) -> {
   System.out.println("Country : " + key + ", Capital : " + value);
  });

  System.out.println("\nCountries and their capitals in upper case");
  countriesMap.forEach((key, value) -> {
   System.out.println("Country : " + key.toUpperCase() + ", Capital : " + value.toUpperCase());
  });
 }
}

Run Test.java, you can see below messages in console.

Countries and their capitals in raw form
Country : Cuba, Capital : Havana
Country : Mongolia, Capital : Ulaanbaatar
Country : Sweden, Capital : Stockholm
Country : Belgium, Capital : Belmopan
Country : Poland, Capital : Warsaw
Country : Georgia, Capital : Tbilisi
Country : Nepal, Capital : Kathmandu

Countries and their capitals in upper case
Country : CUBA, Capital : HAVANA
Country : MONGOLIA, Capital : ULAANBAATAR
Country : SWEDEN, Capital : STOCKHOLM
Country : BELGIUM, Capital : BELMOPAN
Country : POLAND, Capital : WARSAW
Country : GEORGIA, Capital : TBILISI
Country : NEPAL, Capital : KATHMANDU


Previous                                                 Next                                                 Home

No comments:

Post a Comment