Reputation: 4576
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.
Upvotes: 0
Views: 4938
Reputation: 1195
You can use like this -
if(map.get("keyName").equals(null) || map.get("keyName").equals("")){
//Failed to insert code
}
Upvotes: 0
Reputation: 7496
I would suggest you use StringUtils from Apache Commons:
if (!StringUtils.isEmpty(map.get("keyName")){
// Do something
}
See the JavaDoc: https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#isEmpty%28java.lang.String%29
Upvotes: 0
Reputation: 44740
You can do something like this-
String val = map.get("keyName");
if(val != null && !"".equals(val)){
// val is not null and is not empty
}
Upvotes: 1