Java – if it is not null, put the value into the map

Does java have anything similar?

map.putIfValueNotNull(key,value)

Therefore, I can put the value in the map only if it is not empty without explicit check

Solution

I know org apache. commons. collections4. Maputils contains the method safeaddtomap(), but if value is null, an empty string will be added, which is not what you want

I don't like variant. I want to rewrite HashMap to implement the new method, because in this case, you don't have it for other implementations: treemap or LinkedHashMap or others

I didn't know that this function exists in some available libraries, such as Apache or similar

Therefore, in my project, I must 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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>