80

How do you pass in null values into a HashMap?
The following code snippet works with options filled in:

HashMap<String, String> options = new HashMap<String, String>();  
options.put("name", "value");
Person person = sample.searchPerson(options);  
System.out.println(Person.getResult().get(o).get(Id));    

So the issue is what has to be entered into the options and or method to pass in a null value?
I tried the following code without any success:

options.put(null, null);  
Person person = sample.searchPerson(null);    

options.put(" ", " ");  
Person person = sample.searchPerson(null);    

options.put("name", " ");  
Person person = sample.searchPerson(null);  

options.put();  
Person person = sample.searchPerson();    
divanov
  • 6,173
  • 3
  • 32
  • 51
Neutron_boy
  • 919
  • 1
  • 6
  • 7
  • 12
    What does "without any success" imply? What's the problem? Do you get an error message? – Till Helge Feb 26 '13 at 14:09
  • Learn how to use a Map separately, then integrate it into your program. http://docs.oracle.com/javase/6/docs/api/java/util/Map.html – Christophe Roussy Feb 26 '13 at 14:22
  • why we are not getting null pointer exception after adding null as key in the map? – Amit Jan 25 '16 at 13:08
  • `" "` in not a `null` string, it is a string containing a single space character. So to search for that use `" "`. `""` is also not null, it in an empty string. Only `null` is the correct pointer to null. So `put.("name", null);` – Sheldon Jul 18 '17 at 12:24
  • 1
    Ugly, but perhaps create a `Map`. When I see `HashMap` on the left hand side of a variable declaration my inclination is to remove the "Hash". – Sridhar Sarnobat Aug 02 '17 at 21:24

7 Answers7

139

HashMap supports both null keys and values

http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html

... and permits null values and the null key

So your problem is probably not the map itself.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
kenor
  • 1,888
  • 2
  • 16
  • 27
14

You can keep note of below possibilities:

1. Values entered in a map can be null.

However with multiple null keys and values it will only take a null key value pair once.

Map<String, String> codes = new HashMap<String, String>();

codes.put(null, null);
codes.put(null,null);
codes.put("C1", "Acathan");

for(String key:codes.keySet()){
    System.out.println(key);
    System.out.println(codes.get(key));
}

output will be :

null //key  of the 1st entry
null //value of 1st entry
C1
Acathan

2. your code will execute null only once

options.put(null, null);  
Person person = sample.searchPerson(null);   

It depends on the implementation of your searchPerson method if you want multiple values to be null, you can implement accordingly

Map<String, String> codes = new HashMap<String, String>();

    codes.put(null, null);
    codes.put("X1",null);
    codes.put("C1", "Acathan");
    codes.put("S1",null);


    for(String key:codes.keySet()){
        System.out.println(key);
        System.out.println(codes.get(key));
    }

output:

null
null

X1
null
S1
null
C1
Acathan
joschi
  • 12,746
  • 4
  • 44
  • 50
Shuchi Jain
  • 151
  • 1
  • 3
4

It seems that you are trying to call a method with a Map parameter. So, to call with an empty person name the right approach should be

HashMap<String, String> options = new HashMap<String, String>();
options.put("name", null);  
Person person = sample.searchPerson(options);

Or you can do it like this

HashMap<String, String> options = new HashMap<String, String>();
Person person = sample.searchPerson(options);

Using

Person person = sample.searchPerson(null);

Could get you a null pointer exception. It all depends on the implementation of searchPerson() method.

0

Its a good programming practice to avoid having null values in a Map.

If you have an entry with null value, then it is not possible to tell whether an entry is present in the map or has a null value associated with it.

You can either define a constant for such cases (Example: String NOT_VALID = "#NA"), or you can have another collection storing keys which have null values.

Please check this link for more details.

Pritesh Mhatre
  • 3,847
  • 2
  • 23
  • 27
  • Yes, though when refactoring bad code and wanting to preserve null behavior you may still need to insert null into a Map. – Sridhar Sarnobat Aug 02 '17 at 21:22
  • 9
    `If you have an entry with null value, then it is not possible to tell whether an entry is present in the map or has a null value associated with it.`: what about `Map.containsKey`? Or iterating over all entries of map and checking their `Map.Entry.getKey()`? – izogfif Mar 15 '18 at 11:56
0

i was getting hashmap with null values like this

{fieldCode1=F0001, fieldId10=null, fieldId11=null }

i used the method from using Guava library using below link https://www.techiedelight.com/remove-null-values-map-java/

Iterables.removeIf(inputParams.values(), Predicates.isNull());

inputParams is the hashmap

Hashmap value after using the method {fieldCode1=F0001}

Use the below import packages import com.google.common.collect.Iterables; import com.google.common.base.Predicates;

  • Hey, the question already has an answer and you answer does not seem to add any more information, especially because the OP doesn't seem to use Guava as you suggested. You might have a look at https://stackoverflow.com/help/how-to-answer – Moritz Apr 10 '22 at 14:29
-2

Acording to your first code snipet seems ok, but I've got similar behavior caused by bad programing. Have you checked the "options" variable is not null before the put call?

I'm using Struts2 (2.3.3) webapp and use a HashMap for displaying results. When is executed (in a class initialized by an Action class) :

if(value != null) pdfMap.put("date",value.toString());
else pdfMap.put("date","");

Got this error:

Struts Problem Report

Struts has detected an unhandled exception:

Messages:   
File:   aoc/psisclient/samples/PDFValidation.java
Line number:    155
Stacktraces

java.lang.NullPointerException
    aoc.psisclient.samples.PDFValidation.getRevisionsDetail(PDFValidation.java:155)
    aoc.action.signature.PDFUpload.execute(PDFUpload.java:66)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    ...

Seems the NullPointerException points to the put method (Line number 155), but the problem was that de Map hasn't been initialized before. It compiled ok since the variable is out of the method that set the value.

exoddus
  • 2,230
  • 17
  • 27
-7

you can probably do it like this:

String k = null;
String v = null;
options.put(k,v);