Java - Iterate over keys, values, or entries of a Map.

Introduction

The keySet(), values() and entrySet() methods of a map returns a Set of keys, a Collection of values, and a Set of entries, respectively.

The following code shows how to print all keys of a map:

Demo

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

public class Main {
  public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("XML", "(342)113-1234");
    map.put("Javascript", "(245)890-2345");
    map.put("Json", "(205)678-3456");
    map.put("Java", "(205)678-3456");

    // Get the set of keys
    Set<String> keys = map.keySet();

    // Print all keys using the forEach() method.
    // You can use a for-each loop, an iterator, etc. to do the same.
    keys.forEach(System.out::println);
  }//  ww  w . j  a  va 2s  .  c o  m
}

Result

Related Topic