Java Map get() example

In this guide, you will learn about the Map get() method in Java programming and how to use it with an example.

1. Map get() Method Overview

Definition:

The get() method of the Java Map interface retrieves the value to which the specified key is mapped, or null if the map contains no mapping for the key.

Syntax:

V value = map.get(Object key);

Parameters:

- key: The key whose associated value is to be returned.

Key Points:

- If the map contains a mapping for the specified key, this method returns the associated value.

- If the map doesn't contain the specified key, it returns null.

- The method allows null as a key. If the map contains a mapping for a null key, then this method can return the value associated with that key.

- If the map implementation allows for null values, then a return value of null does not necessarily indicate that the map contains no mapping for the key; it could also mean that the map explicitly maps the key to null.

2. Map get() Method Example

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

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

        // Populate the map
        fruitsCount.put("Apple", 10);
        fruitsCount.put("Banana", null);
        fruitsCount.put(null, 5);

        // Get values using keys
        System.out.println(fruitsCount.get("Apple"));     // 10
        System.out.println(fruitsCount.get("Banana"));    // null
        System.out.println(fruitsCount.get("Cherry"));    // null
        System.out.println(fruitsCount.get(null));        // 5
    }
}

Output:

10
null
null
5

Explanation:

In this example:

1. We create a HashMap and populate it with three key-value pairs. One of these pairs has a null key, and another has a null value.

2. We then use the get() method to retrieve the values associated with various keys:

- Retrieving the value for "Apple" gives us 10.

- Retrieving the value for "Banana" gives us null. This indicates that "Banana" is mapped to null, not that "Banana" is absent from the map.

- Retrieving the value for "Cherry" also gives us null, but in this case, it's because "Cherry" is not in the map.

- Finally, retrieving the value for a null key gives us 5.

The get() method is fundamental when working with maps as it provides a way to fetch the value associated with a particular key. It's essential to understand its behavior, especially when dealing with null keys or values.

Related Map Interface methods

Java Map put() example
Java Map get() example
Java Map remove() example
Java Map containsKey() example
Java Map containsValue() example
Java Map keySet() example
Java Map values() example
Java Map entrySet() example

Comments