Does Java have something like
map.putIfValueNotNull(key, value)
So I can put value in the map only if it`s not null without explicit checking.
HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value.
isEmpty and MapUtils. isEmpty() methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").
HashMap puts null key in bucket 0 and maps null as key to passed value. HashMap does it by linked list data structure. HashMap uses linked list data structure internally. In Entry class the K is set to null and value mapped to value passed in put method.
I know that org.apache.commons.collections4.MapUtils
contains method safeAddToMap()
, but if value
is null
, it adds empty string
which is not what you want.
I do not like variant, to override HashMap
to implement new method, because in this case you do not have it for other implementations: TreeMap
or LinkedHashMap
or else.
I do not know about that this function exists in some availabe library, like Apache
or similar.
Therefore, in my projects, I have to implement it myself:
public static <K, V> Map<K, V> addNotNull(Map<K, V> map, K key, V value) {
if(value != null)
map.put(key, value);
return map;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With