get string value from HashMap depending on key name
To get the string value from a HashMap depending on the key name in Java, you can use the get() method of the Map interface.
To get the string value from a HashMap depending on the key name in Java, you can use the get() method of the Map interface. The get() method returns the value associated with the specified key, or null if the key is not found in the map.
Here is an example of how you can use the get() method to get the string value from a HashMap:
import java.util.HashMap;
import java.util.Map;
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
String value = map.get("key2"); // value is "value2"Alternatively, you can use the getOrDefault() method of the Map interface to specify a default value to be returned if the key is not found in the map:
import java.util.HashMap;
import java.util.Map;
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
String value = map.getOrDefault("key4", "default"); // value is "default"Keep in mind that get() and getOrDefault() return null when a key is missing. When using a generic Map<String, String>, the return type matches the declared value type, so explicit casting is not required. Casting is only necessary if you are working with raw Map types. To handle potential null returns safely, you can check for null using java.util.Objects.isNull() or wrap the result in Optional.