Java HashMap get() Method

Java HashMap Java HashMap

The get() method retrieves the value corresponding to the specified key.

The syntax of the get() method is:

hashmap.get(Object key)

Note:hashmap is an object of the HashMap class.

Parameter Details:

  • key - the key

Return Value

Returns the value associated with the specified key.

Example

The following example demonstrates the use of the get() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "Example");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Get the value
        String value = sites.get(1);
        System.out.println("Value for key 1: " + value);
    }
}

The output of running the above program is:

sites HashMap: {1=Google, 2=Example, 3=Taobao}
key 1 对应的 value: Google

Note:We can also useHashMap containsKey() methodto check whether a specific key exists in the HashMap.

Getting an Integer value using a String key:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<String, Integer> primeNumbers = new HashMap<>();

        // Add mappings to HasMap
        primeNumbers.put("Two", 2);
        primeNumbers.put("Three", 3);
        primeNumbers.put("Five", 5);
        System.out.println("HashMap: " + primeNumbers);

        // Get the value
        int value = primeNumbers.get("Three");
        System.out.println("Value for key Three: " + value);
    }
}

The output of running the above program is:

HashMap: {Five=5, Two=2, Three=3}
key Three 对应的 value: 3

In the above example, we used the get() method to obtain the value corresponding to the key "Three".

Java HashMap Java HashMap

Other Extensions