Using Map in Java

A Map in Java stores key-value pairs. Each key maps to at most one value, and a map cannot contain duplicate keys. Map is an interface, and HashMap and TreeMap are two of its implementations. Use put() to add a pair, get() to read a value by its key, containsKey() to check for a key, remove() to delete a pair and size() to count the pairs. In this Java Map Example, we create a HashMap, add two pairs, read a value by its key and print the size of the map. Click Execute to run the Java Map Example online and see the result.
Using Map in Java Execute
import java.util.HashMap;
import java.util.Map;

public class MapExample {

    public static void main(String[] args) {
        Map<String, String> countriesAndCapitals = new HashMap<>();

        countriesAndCapitals.put("France", "Paris");
        countriesAndCapitals.put("Japan", "Tokyo");

        String capitalOfFrance = countriesAndCapitals.get("France");
        System.out.println("Capital of France: " + capitalOfFrance);

        System.out.println("Size of the map: " + countriesAndCapitals.size());
    }
}

Java Map Syntax

Map is an interface in the java.util package. A map is declared with two types: K for the keys and V for the values.

Java Map Syntax
Map<K, V> map = new HashMap<>();
map.put(key, value);
V value = map.get(key);

What is the difference between Map and HashMap?

Map is the interface that defines the operations. HashMap is a class that implements Map with a hash table and makes no guarantees about the order of its keys. TreeMap is another implementation that keeps its keys sorted.

Java Map Examples

The following are examples of using a Map in Java. Run them in the online Java code runner to see what each method returns.

Add and read values

put() adds a key-value pair. If the key is already in the map, put() replaces its value. get() returns null for a missing key, and getOrDefault() returns the default value you pass.

Java Map put() and get() Example
import java.util.HashMap;
import java.util.Map;

public class MapPutGetExample {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        stock.put("apples", 10);
        stock.put("pears", 4);
        stock.put("apples", 12);
        System.out.println(stock.get("apples"));
        System.out.println(stock.get("plums"));
        System.out.println(stock.getOrDefault("plums", 0));
    }
}

// output:
// 12
// null
// 0

Check and remove keys

containsKey() tells whether a key is in the map, remove() deletes the pair for a key, and size() returns the number of pairs.

Java Map containsKey() and remove() Example
import java.util.HashMap;
import java.util.Map;

public class MapRemoveExample {
    public static void main(String[] args) {
        Map<String, String> capitals = new HashMap<>();
        capitals.put("France", "Paris");
        capitals.put("Japan", "Tokyo");
        System.out.println(capitals.containsKey("Japan"));
        capitals.remove("Japan");
        System.out.println(capitals.containsKey("Japan"));
        System.out.println(capitals.size());
    }
}

// output:
// true
// false
// 1

Loop through a Map

entrySet() returns the key-value pairs as a Set that a for-each loop can walk through. A HashMap returns the pairs in no guaranteed order. A TreeMap, as in this example, returns them sorted by key.

Java Map entrySet() Loop Example
import java.util.Map;
import java.util.TreeMap;

public class MapLoopExample {
    public static void main(String[] args) {
        Map<String, Integer> scores = new TreeMap<>();
        scores.put("Carol", 7);
        scores.put("Alice", 9);
        scores.put("Bob", 5);
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

// output:
// Alice: 9
// Bob: 5
// Carol: 7

See also

Updated: