Java - Collection Framework Maps

Introduction

A map contains key-value mappings.

A <key, value> pair is also known as an entry in the map.

The key and the value must be reference types. You cannot use primitive types (int, double, etc.) for either keys or values in a map.

A map is represented by Map<K,V> interface which is not inherited from the Collection interface.

A Map cannot have any duplicate keys and each key is mapped to one value.

Two keys may map to the same value.

Map allows for at most one null value as its key and multiple null values as its values.

HashMap, LinkedHashMap, and WeakHashMap are three of the implementation classes for the Map interface.

HashMap allows one null value as a key and multiple null values as the values.

A HashMap does not guarantee any specific iteration order of entries in the Map.

// Create a map using HashMap as the implementation class
Map<String, String> map = new HashMap<>();

// Put an entry to the map - "XML" as the key and "(123)123-1234" as the value
map.put("XML", "(123)123-1234");

LinkedHashMap stores entries in the Map using a doubly linked list.

It keeps the iteration ordering as the insertion order.

The following code demonstrates how to use a Map.

Demo

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

public class Main {
  public static void main(String[] args) {
    // Create a map and add some key-value pairs
    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");

    // Print the details
    printDetails(map);/*from   w  w w. j  a va  2s. co m*/

    // Remove all entries from the map
    map.clear();

    System.out.printf("%nRemoved all entries from the map.%n%n");
    // Print the details
    printDetails(map);
  }

  public static void printDetails(Map<String, String> map) {
    // Get the value for the "Json" key
    String donnaPhone = map.get("Json");

    // Print details
    System.out.println("Map: " + map);
    System.out.println("Map Size: " + map.size());
    System.out.println("Map is empty: " + map.isEmpty());
    System.out.println("Map contains Json key: " + map.containsKey("Json"));
    System.out.println("Json Phone: " + donnaPhone);
    System.out.println("Json key is removed: " + map.remove("Json"));
  }
}

Result

Related Topics