Java HashMap.get()

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()

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

The syntax of get() function is

</>
Copy
get(Object key)

where

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

Returns

The function returns value.

Examples

1. Get value from HashMap for a key, where key is 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

</>
Copy
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

2. HashMap get(key) when key is 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

</>
Copy
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.