Java HashMap.get() – Examples

In this tutorial, we will learn about the Java HashMap.get() function, and learn how to use this function to get the value of specific key, with the help of examples.

get(Object key)

HashMap.get() Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Syntax

The syntax of get() function is

get(Object key)

where

ParameterDescription
keyThe key whose value in this HashMap has to be returned.

Returns

The function returns value.

Example 1 – get(Object key) – Key Present

In this example, we will initialize a HashMap hashMap with mappings from Integer to String. To get the value corresponding to key “3”, we will use HashMap.get() method.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<Integer, String> hashMap = new HashMap<>();
		hashMap.put(1, "A");
		hashMap.put(2, "B");
		hashMap.put(3, "C");
		hashMap.put(4, "D");
		
		int key = 2;
		String value = hashMap.get(key);
		System.out.println("The value for key \"" + key + "\" is : " + value);
	}
}

Output

The value for key "2" is : B

Example 2 – get(Object key) – Key not Present

In this example, we will initialize a HashMap hashMap with mappings from Integer to String. To get the value corresponding to key “5”, we will use HashMap.get() method. Since, the specified key is not present in this HashMap, get() returns null.

Java Program

import java.util.HashMap;

public class Example{ 
	public static void main(String[] args) {
		HashMap<Integer, String> hashMap = new HashMap<>();
		hashMap.put(1, "A");
		hashMap.put(2, "B");
		hashMap.put(3, "C");
		hashMap.put(4, "D");
		
		int key = 5;
		String value = hashMap.get(key);
		System.out.println("The value for key \"" + key + "\" is : " + value);
	}
}

Output

The value for key "5" is : null

Conclusion

In this Java Tutorial, we have learnt the syntax of Java HashMap.get() function, and also learnt how to use this function with the help of examples.