βThe Map.get() method in Java retrieves the value associated with a specific key in a map. If the key does not exist, it returns null. The return type of get() depends on the type of values stored in the map.
Example 1: Integer as Value Type
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 10);
map.put("B", 20);
System.out.println(map.get("A")); // Output: 10
System.out.println(map.get("C")); // Output: null
}
}
In this example, the return type of get() is Integer because the map stores integers as values.
Example 2: String as Value Type
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
System.out.println(map.get(1)); // Output: One
System.out.println(map.get(3)); // Output: null
}
}
Here, the return type of get() is String since the map stores strings as values.
Key Considerations
The return type of get() is determined by the value type specified during the map's declaration.
If the key does not exist in the map, null is returned.
Using primitive types like int or double as keys or values requires their wrapper classes (Integer, Double, etc.) due to Java's generics system.