Easy Tutorial
❮ Java Arraylist Lastindexof Number Equals ❯

Java HashMap get() Method

Java HashMap

The get() method retrieves the value associated with the specified key.

The syntax for the get() method is:

hashmap.get(Object key)

Note: hashmap is an object of the HashMap class.

Parameter:

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&lt;Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "tutorialpro");
        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);
    }
}

Execution of the above program produces the following output:

sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Value for key 1: Google

Note: We can also use the HashMap containsKey() method to check if a specific key exists in the HashMap.

Using a String key to retrieve an Integer value:

Example

import java.util.HashMap;

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

        // Add mappings to the HashMap
        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);
    }
}

Execution of the above program produces the following output:

HashMap: {Five=5, Two=2, Three=3}
Value for key Three: 3

In the above example, we used the get() method to retrieve the value associated with the key "Three".

Java HashMap

❮ Java Arraylist Lastindexof Number Equals ❯