Iterate or loop EnumMap using entrySet & forEach Java 8 (example)

  • Given an EnumMap containing key value pairs in java.
  • EnumMap is specialized Map implementation, to use enum as key(s).
  • Enum maps are maintained in the natural order of their keys (the order in which the enum constants are declared).
  • EnumMap will containing enum as its key.
    • e.g EnumMap will contain key, enum of Human development index and value, the list of countries.

Iterate or loop through EnumMap in java

  1. Iterate or loop EnumMap using entrySet iterator.
    • Iterate EnumMap using entrySet iterator.
  2. Iterate or loop EnumMap using forEach (java 8)
    • Iterate EnumMap using forEach loop in java 8.

Program: loop or iterate through EnumMap in java

package org.learn.collection.map.emap;

import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

enum HDI {
 Very_High, High, Medium, Low
}

public class DemoEnumMap {

 public static void main(String[] args) {
  Map<HDI, List<String>> enumHDIAndCountries = new EnumMap<>(HDI.class);
  enumHDIAndCountries.put(HDI.Very_High, Arrays.asList("Norway", "Australia", "Switzerland"));
  enumHDIAndCountries.put(HDI.High, Arrays.asList("Belarus", "Russia", "Oman"));
  enumHDIAndCountries.put(HDI.Medium, Arrays.asList("Botswana", "Moldova", "Egypt"));
  enumHDIAndCountries.put(HDI.Low, Arrays.asList("Kenya", "Angola", "Nigeria"));

  System.out.println("Method 1 - Iterate EnumMap: ");
  demoIterateEnumMap(enumHDIAndCountries);

  System.out.println("\nMethod 2 - Iterate EnumMap using java 8: ");
  demoIterateEnumMapJava8(enumHDIAndCountries);
 }

 private static void demoIterateEnumMap(Map<HDI, List<String>> enumHDIAndCountries) {
  for (Entry<HDI, List<String>> entry : enumHDIAndCountries.entrySet()) {
   HDI vehicleNumber = entry.getKey();
   List<String> owner = entry.getValue();
   System.out.println("HDI:" + vehicleNumber + ", Countries:" + owner);
  }
 }

 private static void demoIterateEnumMapJava8(Map<HDI, List<String>> enumHDIAndCountries) {
  enumHDIAndCountries.forEach((key, value) -> {
   System.out.println("HDI:" + key + ", Countries:" + value);
  });
 }
}

Output – iterate through EnumMap using entrySet or forEach in java

Method 1 - Iterate EnumMap: 
HDI:Very_High, Countries:[Norway, Australia, Switzerland]
HDI:High, Countries:[Belarus, Russia, Oman]
HDI:Medium, Countries:[Botswana, Moldova, Egypt]
HDI:Low, Countries:[Kenya, Angola, Nigeria]

Method 2 - Iterate EnumMap using java 8: 
HDI:Very_High, Countries:[Norway, Australia, Switzerland]
HDI:High, Countries:[Belarus, Russia, Oman]
HDI:Medium, Countries:[Botswana, Moldova, Egypt]
HDI:Low, Countries:[Kenya, Angola, Nigeria]
Scroll to Top