The get() method of the Map interface in Java is used to retrieve the value associated with a specific key. If the key is not present in the map, it returns null.
Syntax:
V get(Object key)
- Parameter: "key" – the key whose mapped value is to be returned.
- Return Value: Returns the value associated with the specified key, or null if the key is not found.
- Return Type: Depends on the value type stored in the map.
Example 1: Map with String keys and Integer values
import java.util.*;
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("Geeks", 10);
map.put("4", 15);
map.put("Geeks", 20); // overwrites previous value
map.put("Welcomes", 25);
map.put("You", 30);
System.out.println("Initial Mappings: " + map);
// Retrieve values using get()
System.out.println("Value of 'Geeks': " + map.get("Geeks"));
System.out.println("Value of 'You': " + map.get("You"));
}
}
Output
Initial Mappings: {4=15, Geeks=20, You=30, Welcomes=25}
Value of 'Geeks': 20
Value of 'You': 30
Note: If the key already exists, put() overwrites the previous value.
Example 2: Map with Integer keys and String values
import java.util.*;
public class MapDemo {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(10, "Geeks");
map.put(15, "4");
map.put(20, "Geeks");
map.put(25, "Welcomes");
map.put(30, "You");
System.out.println("Initial Mappings: " + map);
// Retrieve values using get()
System.out.println("Value of key 25: " + map.get(25));
System.out.println("Value of key 10: " + map.get(10));
}
}
Output
Initial Mappings: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Value of key 25: Welcomes
Value of key 10: Geeks
Points to remember:
- get() works with any key-value combination (e.g., String-Integer, Integer-String, custom objects).
- Returns null if the key does not exist.
- Map keys are unique; calling put() with an existing key overwrites the old value.