Is it possible that I can put values directly to the key has null values of HashMap
?
What I want is to check if the value of one key in HashMap
is null
then i'm going to fill it.
If map.get(key)
returns null, you know that either the key is not present in the Map or that it's present and has a null value.
To distinguish between the two :
if (map.containsKey(key)) {
if (map.get(key) == null) {
// key is present and has null value
}
} else {
// key is not present in the Map
}
In addition to @Eran answer I should note that having null
values in Map
is discouraged. First, it's not supported by every Map implementation. For example, ConcurrentHashMap
does not support null
values, so if later this Map
will be shared across several threads and you decide to move to ConcurrentHashMap
you will discover that you cannot do this without getting rid of nulls. Second, most of the new Java-8 API methods getOrDefault
, merge
, computeIfAbsent
do not behave friendly with null
values: usually they assume that null
value is the same as the absence of the value. Finally handling null
values is somewhat slower as you need to check against the same key twice (first via containsKey
, second via get
).
Thus in general if it's possible you should avoid null values in maps. Sometimes it's possible to introduce a special constant which designates an absence of the value. That depends on particular task.
Here is the simplest (can be improved/code reviewed further) complete program. It will find the key
and if the corresponding value is null
it will replace that null with yourNewValue.
import java.util.HashMap;
import java.util.Map;
public class SimpleMapKeyValue {
public static void main(final String[] args) throws Exception {
final Map<String, Integer> map = new HashMap<>();
map.put("A", 5);
map.put("B", 10);
map.put("D", null);
map.put("E", 23);
int yourNewValue = 100;
for(Map.Entry<String, Integer> entry : map.entrySet()){
if (entry.getValue() == null) {
map.put(entry.getKey(),yourNewValue);
}
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.