java.util.HashMap get(Object key)

Description :

On this document we will be showing a java example on how to use the get(Object Key) method of HashMap Class. Basically this method returns the value which corresponds to the key specified as method argument. From this premise what do you think would be the type of the key that is required? And also what would be the type of the returned value? That would be depending on how we instantiated our HashMap. Please take a look below on how to instantiate a HashMap object:

HashMap<Integer,String> map = new HashMap<Integer,String>();

From the above code snippet, the key would be Integer while the value is String. So it means that we need to pass an Integer object or its subclass as the key and we are expecting a value to be returned as String or its subclass. So that would mean, are we restricted to use these types? Yes and No. Yes if we are referring to the above example wherein we explicitly specify the type of the key-value set. If you specify different type of object for the key value pair, it is expected for you to use the same type. If you are interested to learn more about this, please visit the official oracle documentation of Generics.

Important notes for get method:

  • specified by isEmpty¬†in interface Map<K,V>
  • overrides isEmpty¬†in class AbstractMap<K,V>

Method Syntax :

public V get(Object key)

Parameter Input :

[table]
DataType|Parameter|Description
Object|key|the key of the value which we are interested to be retrieved from the HashMap
[/table]

Method Returns :

The get() method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key

Compatibility Version :

Requires Java 1.2 and up

Exception :

N/A

Java Code Example :

This java example source code demonstrates the use of get() method of HashMap class. From the example below, basically we have a method init() which actually do the assignment of values to the HashMap object which are expected to be returned by this method. The HashMap returned by the init() method is having an Integer object as key and String object as values. We then used the returned HashMap to print the values using the student id as key.

Sample Output :

Running the above java example of the usage of HashMap get() method will give the following output:

HashHamp isEmpty() method example

HashHamp isEmpty() method example Output

Similar Method :

The following are the list of method that you can go through for better understanding of the presented example

  • HashMap put()

Suggested Reading List :

References :