The get()
method returns the value corresponding to the specified key in the hashmap.
Example
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create an HashMap
HashMap<Integer, String> numbers = new HashMap<>();
numbers.put(1, "Java");
numbers.put(2, "Python");
numbers.put(3, "JavaScript");
// get the value with key 1
String value = numbers.get(1);
System.out.println("HashMap Value with Key 1: " + value);
}
}
// Output: HashMap Value with Key 1: Java
Syntax of HashMap get()
The syntax of the get()
method is:
hashmap.get(Object key)
Here, hashmap is an object of the HashMap
class.
get() Parameters
The get()
method takes a single parameter.
- key - key whose mapped value is to be returned
get() Return Value
- returns the value to which the specified key is associated
Note: The method returns null
, if either the specified key is mapped to a null value or the key is not present on the hashmap.
Example 1: Get String Value Using Integer Key
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create an HashMap
HashMap<Integer, String> numbers = new HashMap<>();
// insert entries to the HashMap
numbers.put(1, "Java");
numbers.put(2, "Python");
numbers.put(3, "JavaScript");
System.out.println("HashMap: " + numbers);
// get the value
String value = numbers.get(3);
System.out.println("The key 3 maps to the value: " + value);
}
}
Output
HashMap: {1=Java, 2=Python, 3=JavaScript} The key 3 maps to the value: JavaScript
In the above example, we have created a hashmap named numbers. The get()
method is used to access the value Java to which the key 1 is associated with.
Note: We can use the HashMap containsKey() method to check if a particular key is present in the hashmap.
Example 2: Get Integer Value Using String Key
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create an HashMap
HashMap<String, Integer> primeNumbers = new HashMap<>();
// insert entries 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("The key Three maps to the value: " + value);
}
}
Output
HashMap: {Five=5, Two=2, Three=3} The key Three maps to the value: 3
In the above example, we have used the get()
method to get the value 3 using the key Three.
Also Read: