Akeshwar Akeshwar - 1 year ago 110
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.

Answer Source

You can do something like this-

String val = map.get("keyName");
if(val != null && !"".equals(val)){
    // val is not null and is not empty
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download