Null check hashmap key

I have a script where I need to check null. I have a key with the name dT:

String dT = (String) caseChk.get("dT");

This returns a NullPointerException, since this key itself does not exist. If I check with

if(caseChk.get("dT") != null) {
    // do something
}

another one NullPointerExceptionselected due .get. How can I check for nullwhen the key on the card does not exist? I understand that a method putshould handle it, but this is not under my control.]

0
source share
6 answers

Even now I get nullpoiner since .get throws exception

If caseChk.get("dT")- this is only the string that you have, and, of course, it throws an exception, then only the possibility caseChkcan be zero.

+10

, , HashMap#containsKey(key). , HashMap#get(key), .

+2

caseChk coud be null try this

 String dT;
if(chaseChk!= null) 
dT= (String)caseChk.get("dT");`
0
source

Try using this method to check for null

public String checkNull_HashMap (hashMap hash table, hashKey string) {

    if (hashMap.get(hashKey) == null) {
        return "";
    } else {
        return hashMap.get(hashKey).toString();
    }
}
0
source

The best option is to check for null before calling toString()

if ( hashMap.get(hashKey) != null ) { return hashMap.get(hashKey).toString(); }
0
source

Try it, it will work.

    if(!caseChk.isEmpty)
    {
      String dT = (caseChk.containsKey("dT")?(String)caseChk.get("dT"):" ")
    }   
0
source

All Articles