Java - Using Keys, Values, and Entries Views of a Map

Description

Using Keys, Values, and Entries Views of a Map

Demo

import java.util.Collection;
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");

    System.out.println("Map: " + map.toString());

    // Print keys, values, and entries in the map
    listKeys(map);//from  w  ww.  jav a 2 s.  c  o m
    listValues(map);
    listEntries(map);
  }

  public static void listKeys(Map<String, String> map) {
    System.out.println("Key Set:");
    Set<String> keys = map.keySet();
    keys.forEach(System.out::println);
    System.out.println();
  }

  public static void listValues(Map<String, String> map) {
    System.out.println("Values Collection:");
    Collection<String> values = map.values();
    values.forEach(System.out::println);
    System.out.println();
  }

  public static void listEntries(Map<String, String> map) {
    System.out.println("Entry Set:");

    // Get the entry Set
    Set<Map.Entry<String, String>> entries = map.entrySet();
    entries.forEach((Map.Entry<String, String> entry) -> {
      String key = entry.getKey();
      String value = entry.getValue();
      System.out.println("key=" + key + ", value=" + value);
    });
  }
}

Result

Related Topic