import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
public class HelloWorld{
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
IntStream.range(0, 20).forEach(i -> map.put(Integer.toString(i), i % 2 == 0 ? null : "ok"));
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getValue() == null) {
map.remove(entry.getKey());
}
}
}
}
This is a sample code where I am trying to delete the null values off the given Hashmap. But this code is giving ConcurrentModificationException. Any idea how to fix this?
EDIT: Thanks to YCF_L, the above code helps if I replace the whole loop with the map.entrySet().removeIf(entity -> entity.getValue() == null);
Problem 2:
What if the hashmap is nested?
- Case 1 -> I want to delete if value is null
- Case 2 -> I want to delete if the value is a hashmap whose each element in the nested hash is null and so on if its nested nested.
Ex code:
public static void removeEmptyValues(Map<String, Object> entityMap) {
for (Map.Entry<String, Object> entry : entityMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value == null) {
entityMap.remove(key);
} else if (value instanceof Map) {
removeEmptyValues((Map) value);
if (((Map) value).isEmpty()) {
entityMap.remove(key);
}
}
}
}