English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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)
key - to return its mappingvalueKey
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.
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.
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.