Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put value into map if not null

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.

like image 827
David Avatar asked Jan 05 '18 15:01

David


People also ask

IS NULL value allowed in map?

HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value.

Does map isEmpty check for null?

isEmpty and MapUtils. isEmpty() methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").

How do I assign a null value to a map?

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.


1 Answers

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;
}
like image 187
oleg.cherednik Avatar answered Oct 11 '22 12:10

oleg.cherednik