Groovy remove null elements from a map
Asked Answered
R

1

7

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: enter image description here

I had done the next code, but without satisfactory results:

map.values().removeAll(Collections.singleton(null))

Any ideas?

Thanks

Ronnie answered 15/4, 2019 at 20:4 Comment(0)
T
11

Edit

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]

Previous answer:

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]
Tiepolo answered 15/4, 2019 at 20:15 Comment(2)
I got this issue: groovy.lang.MissingMethodException: No signature of method: java.util.LinkedHashMap.removeAll() is applicable for argument types: (DUMMY$_closure1$_closure2) values: [DUMMY$_closure1$_closure2@303fb448] Possible solutions: remove(java.lang.Object), remove(java.lang.Object), remove(java.lang.Object, java.lang.Object), replaceAll(java.util.function.BiFunction), replaceAll(java.util.function.BiFunction)Ronnie
@Ronnie I have edited the answer to the classic Groovy ways.Tiepolo

© 2022 - 2024 — McMap. All rights reserved.