Java 25 (LTS) reference · Map and HashMap Methods

Java Map get() Method

Return the value for a key, or null if the key isn't present. Use getOrDefault() to avoid nulls.

Java 25 (LTS) Since Java 1.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

map.get(key)

Parameters

ParameterDescription
key
Object
The key to look up.

Return value

The value, or null.

Examples

Present and missing keys
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>(Map.of("mug", 12));
        System.out.println(stock.get("mug"));
        System.out.println(stock.get("kettle"));
    }
}

Output

12
null

Run this on your computer — see “Get Started” for setup.

The unboxing trap
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        try {
            int qty = stock.get("kettle");  // unboxing null
        } catch (NullPointerException e) {
            System.out.println("get() returned null: use getOrDefault()");
        }
    }
}

Output

get() returned null: use getOrDefault()

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 1.0Added

Was this page helpful?