Maps

Maps are Java’s built-in associative data type, often called hashes or dictionaries in other languages.

To create an empty map, use the HashMap class from the java.util package:

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

public class MapExample {
    public static void main(String[] args) {
        Map<String, Integer> m = new HashMap<>();

        // Set key/value pairs
        m.put("k1", 7);
        m.put("k2", 13);

        // Printing a map shows all key/value pairs
        System.out.println("map: " + m);

        // Get a value for a key
        int v1 = m.get("k1");
        System.out.println("v1: " + v1);

        // If the key doesn’t exist, the map returns null
        Integer v3 = m.get("k3");
        System.out.println("v3: " + v3);

        // The size method returns the number of key/value pairs
        System.out.println("len: " + m.size());

        // The remove method removes key/value pairs
        m.remove("k2");
        System.out.println("map: " + m);

        // There is no built-in clear method for removing all key/value pairs,
        // but you can use the clear method from the Map interface
        m.clear();
        System.out.println("map: " + m);

        // Check if a key is present in the map
        boolean prs = m.containsKey("k2");
        System.out.println("prs: " + prs);

        // You can also declare and initialize a new map in the same line
        Map<String, Integer> n = new HashMap<>() {{
            put("foo", 1);
            put("bar", 2);
        }};
        System.out.println("map: " + n);

        // Additional utility functions are provided by the Collections class
        Map<String, Integer> n2 = new HashMap<>() {{
            put("foo", 1);
            put("bar", 2);
        }};
        if (n.equals(n2)) {
            System.out.println("n == n2");
        }
    }
}

To run the program, place the code in MapExample.java and compile and run it using the javac and java commands.

$ javac MapExample.java
$ java MapExample
map: {k1=7, k2=13}
v1: 7
v3: null
len: 2
map: {k1=7}
map: {}
prs: false
map: {bar=2, foo=1}
n == n2

Note that maps appear in the form map[k=v, k=v] when printed with System.out.println.

Next example: Functions.