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)
The get()
method takes a single mandatory parameter, i.e., the key for which the associated value must be found.
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
.
The code below shows how the get()
method works in Java:
import java.util.HashMap;class Main {public static void main(String[] args){// initializing HashMapHashMap<String, Integer> vehicles = new HashMap<>();// populating HashMapvehicles.put("Car", 1);vehicles.put("Bus", 2);vehicles.put("Truck", 3);// extracting corresponding valuesSystem.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"));}}
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 returns null
.
Free Resources