Java - Collection Framework Map Entry

Introduction

Each key-value pair in a map is called an entry which is represented by Map.Entry<K,V> interface.

Map.Entry is an inner static interface of the Map interface.

It has three methods called getKey(), getValue(), and setValue(), which return the key of the entry, the value of the entry, and sets a new value in the entry, respectively.

The following code iterates over an entry set 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 entry Set
    Set<Map.Entry<String, String>> entries = map.entrySet();

    // Print all key-value pairs using the forEach() method of the Collection
    // interface.
    // You can use a for-each loop, an iterator, etc. to do the same.
    entries.forEach((Map.Entry<String, String> entry) -> {
      String key = entry.getKey();
      String value = entry.getValue();
      System.out.println("key=" + key + ", value=" + value);
    });/*from w w  w.  jav a 2s  .com*/

  }
}

Result