How to Retrieve a Specific Value From a HashMap Using Key?
Last Updated :
09 Feb, 2024
A HashMap is a data structure that implements a map interface in Java. It stores key-value pairs. On the key object’s hashcode, it uses a hashing function for computing an index-based element. And it is used to store and retrieve values. This allows very fast lookup, addition, and removal of key-value pairs, with average O(1) time complexity.
In this article, we will learn how to retrieve a specific value from a HashMap using its key in Java.
Syntax:
HasMap.get(object key_element)
Program to Retrieve a Specific Value From a HashMap Using Key in Java
Below is the implementation of retrieving a specific value from a HashMap using its key:
Java
import java.util.HashMap;
public class Main
{
public static void main(String[] args)
{
HashMap<String, Integer> courses = new HashMap<>();
courses.put( "Java" , 30000 );
courses.put( "C++" , 25000 );
courses.put( "Python" , 35000 );
String key = "Java" ;
Integer value = courses.get(key);
System.out.println(value);
}
}
|
Explanation of the above Program:
- In the above program, a HashMap is created to store String keys and Integer values.
- Key-value pairs are added using the put() method.
- The key “Java” is used to retrieve the value.
- The get() method is called on the map, passing the key as a parameter.
- This returns the Integer value mapped to “Java”, which is 30000.
- The value is printed to verify it was retrieved correctly.
Note: The get() method returns the value or null if key is not found.
Share your thoughts in the comments
Please Login to comment...