I am getting a map in my method from another server and I have some null values, I wanted to remove those ones, because I am struggling with those values in the following process:
My map looks something like:
I had done the next code, but without satisfactory results:
map.values().removeAll(Collections.singleton(null))
Any ideas?
Thanks
Map doesn't allow duplicate keys, but it allows duplicate values. HashMap and LinkedHashMap allows null keys and null values but TreeMap doesn't allow any null key or value.
In Groovy, there is a subtle difference between a variable whose value is null and a variable whose value is the empty string. The value null represents the absence of any object, while the empty string is an object of type String with zero characters.
The Groovy way, is to filter the entries you want:
def map = [a:42, b:null]
def cleanMap = map.findAll{ it.value!=null }
println cleanMap
// => [a:42]
Seems to work with Jdk8/Groovy 2.5, but not for OP
To remove all elements with a value with null
, remove on the map directly:
def map = [a:42, b:null]
map.removeAll{ it.value == null }
println map
// => [a:42]
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