Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java

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

Talha Ashar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

java

CONTRIBUTOR

Talha Ashar
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring