Akeshwar Akeshwar - 11 months ago 50
Java Question

JAVA: maps and return type of Map.get

I have a hashmap of key and value both of String type.

Map<String, String> map = new HashMap<>();
//put the key-values now

I want to check for null or emptiness of the value of a particular key. Referencing the discussion here, I do it as:

if("".equals(map.get("keyName")) {
//do stuff

Is it valid?
As the return type of Map.get is Object, so do I need to check it like this:

if("".equals(map.get("keyName").toString()) {
//do stuff

But toString() gives null pointer exception if it is null. So, what is the right way to do it?
Yes, I'm a beginner.


You can do something like this-

String val = map.get("keyName");
if(val != null && !"".equals(val)){
    // val is not null and is not empty