0
votes

I have a HashMap object which will be stored in NoSQL database. When it has entries, it would look like:

"input":{"key1": "value1", "key2": "value2" }

If this "input" does not exist in the db, I want "input":{} to be shown in response instead of "input":null. What is the best way to do that?

Thanks

3

3 Answers

3
votes

Initialize it into an empty HashMap by default. If the input value is present set it. Otherwise keep it as the default.

Map<String, String> input = Collections.emptyMap();

Notice that the use of static factory methods is generally preferred to constructors.

2
votes

You need to initialize your map to a non-null instance. If it is empty, you may assign to Collections.emptyMap(), which returns an empty map (immutable). This map is serializable.

map = Collections.emptyMap();

Instantiating a new HashMap every time will unnecessarily allocate memory in your JVM and hence increase load on GC

0
votes

Assuming both your key and value are of type String, in your application, set a condition that if input-not-exist set result as or directly return new HashMap<String,String>()