What is the get() method of the HashMap class in Java?

The get() method of the HashMap class in Java returns the value that corresponds to a specified key in a HashMap instance.

The process is illustrated below:

To use the get() method, you will need to import the HashMap class into the program, as shown below:

import java.util.HashMap;

The prototype of the get() method is shown below:

public V get(Object key)

Parameters

The get() method takes a single mandatory parameter, i.e., the key for which the associated value must be found.

Return value

The get() method returns the value that corresponds to the specified key. If no mapping exists for the provided key, the get() method returns null.

Example

The code below shows how the get() method works in Java:

import java.util.HashMap;
class Main {
public static void main(String[] args)
{
// initializing HashMap
HashMap<String, Integer> vehicles = new HashMap<>();
// populating HashMap
vehicles.put("Car", 1);
vehicles.put("Bus", 2);
vehicles.put("Truck", 3);
// extracting corresponding values
System.out.println("The value corresponding to \"Car\" is: " + vehicles.get("Car"));
System.out.println("The value corresponding to \"Bus\" is: " + vehicles.get("Bus"));
System.out.println("The value corresponding to \"Truck\" is: " + vehicles.get("Truck"));
System.out.println("The value corresponding to \"Bike\" is: " + vehicles.get("Bike"));
}
}

Explanation

First, a HashMap object vehicles is initialized.

Next, key-value pairs are inserted into the HashMap. All entries have unique values.

The get() method proceeds to return the values associated with each key in the HashMap, which are output accordingly. Since the HashMap has no entries with the key “Bike”, the get() method in line 1818 returns null.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved