kumar
kumar

Reputation: 3025

how to validate map is null or not in generic

I need to validate a Map value is null or not,since I work offen with collections,willing to implement generic way of validating the map value,so tried this

public boolean checkNull(Map<String,Object> data){

        if(data != null && !data.isEmpty()){
            return true;
        }
        return false;
    }

now I can able to validate my map only with key as string and value as object,but I also need to check this null condition with any type of map Map or Map.etc, so how can I do a generic function to validate this map process.

  public boolean checkNull(Map<K,V> data){

            if(data != null && !data.isEmpty()){
                return true;
            }
            return false;
        }

will some one can help me to understand this logic in deep.

Upvotes: 0

Views: 158

Answers (3)

Narmer
Narmer

Reputation: 1454

Use this:

public <K, V> boolean checkNull(Map<K, V> entry){
    if(entry!=null&&!entry.isEmpty()){
        return true;
    }
    return false;
}

You can then call <String, Integer> checkNull(myStringAndIntegerMapInstance) which ensure also type reference issues at runtime. See javadoc for more.

Upvotes: 0

laune
laune

Reputation: 31290

 public boolean checkNull(Map<String,?> data){

       // and you can also use this instead of the if:
       return data != null && !data.isEmpty();
    }

or

 public boolean checkNull(Map<?,?> data){

depending on what is known or should be checked by the compiler.

Upvotes: 2

Vadim Fedorenko
Vadim Fedorenko

Reputation: 2561

Try to replace Map<K,V> data to Map<?, ?> data

Upvotes: 0

Related Questions