English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I)/O)

Java Reader/Writer

Java Other Topics

Java HashMap get() usage and example

Java HashMap Methods

The Java HashMap get() method returns the value corresponding to the specified key in the hash map.

The syntax of the get() method is:

hashmap.get(Object key)

get() parameter

  • key - to return its mappingvalueKey

get() returns value

  • Returns the value associated with the specified key

Note: If the specified key maps to a null value or the key does not exist in the hash map, this method returns null.

Example1: Retrieve string value using integer key

import java.util.HashMap;
class Main {
    public static void main(String[] args) {
        //Create HashMap
        HashMap<Integer, String> numbers = new HashMap<>();
        //Insert Entry into HashMap
        numbers.put(1, "Java");
        numbers.put(2, "Python");
        numbers.put(3, "JavaScript");
        System.out.println("HashMap: " + numbers);
        //Get Value
        String value = numbers.get(1);
        System.out.println("Key1Mapped to value: " + value);
    }
}

Output Result

HashMap: {1=Java, 2=Python, 3=JavaScript}
Key1Mapping to value: Java

In the above example, we created a hash map named numbers. The get() method is used to access the Java value associated with the key1the associated value.

Note: We can useHashMap containsKey()method to check if a specific key exists in the hash map.

Example2: Retrieve integer value using string key

import java.util.HashMap;
class Main {
    public static void main(String[] args) {
        //Create HashMap
        HashMap<String, Integer> primeNumbers = new HashMap<>();
        //Insert Entry into HashMap
        primeNumbers.put("Two", 2);
        primeNumbers.put("Three", 3);
        primeNumbers.put("Five", 5);
        System.out.println("HashMap: " + primeNumbers);
        //Get Value
        int value = primeNumbers.get("Three");
        System.out.println("Key3Mapped to value: " + value);
    }
}

Output Result

HashMap: {Five=5, Two=2, Three=3}
Key3Mapped to value: 3

In the above example, we use the get() method to retrieve the value by the key 'Three'3.

Java HashMap Methods