groovy 我可以使用collect或findAll来过滤嵌套的Map吗?

hc8w905p  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(212)

这是我要筛选的唐飞:

def myMap = [
'myMap':[
   // Collect keyOne
   "keyOne": [
           "fieldOne": "blah",
           "fieldTwo": "blah",
           "checkIfThisIsSetToTrue": true,
   ],
   // Do not collect keyTwo
   "keyTwo": [
           "fieldOne": "blah",
           "fieldTwo": "blah",
           "checkIfThisIsSetToTrue": false,
   ],
   // Do not collect keyThree
   "keyThree": [
           "fieldOne": "blah",
           "fieldTwo": "blah",
           //checkIfThisIsSetToTrue not set at all here
   ],
]]

我只想返回checkIfThisIsSetToTrue == true的项。checkIfThisIsSetToTrue也可以为空。
我知道我可以像这样循环遍历它,并将项目添加到新Map:

myMap.each { key, val ->
  if (val?.checkIfThisIsSetToTrue):
    ...
}

但我认为使用collectfindAll会更简洁和更时髦。
我试着这样过滤它:

def myVar = myMap.findAll { it?.checkIfThisIsSetToTrue == true }
def myVar = myMap.any{ it?.checkIfThisIsSetToTrue == true }
def myVar = myMap.collect{ it?.checkIfThisIsSetToTrue == true }

但我得到的错误:

No such property: checkIfThisIsSetToTrue for class: java.util.LinkedHashMap$Entry
lsmd5eda

lsmd5eda1#

你可以这样做:

def myMap = [
'myMap':[
   // Collect keyOne
   "keyOne": [
           "fieldOne": "blah",
           "fieldTwo": "blah",
           "checkIfThisIsSetToTrue": true,
   ],
   // Do not collect keyTwo
   "keyTwo": [
           "fieldOne": "blah",
           "fieldTwo": "blah",
           "checkIfThisIsSetToTrue": false,
   ],
   // Do not collect keyThree
   "keyThree": [
           "fieldOne": "blah",
           "fieldTwo": "blah",
           //checkIfThisIsSetToTrue not set at all here
   ],
]]

// unclear why there is a nested
// myMap in the sample but there is
def innerMyMap= myMap.myMap

def selectedMaps = innerMyMap.findAll {
    it.value.checkIfThisIsSetToTrue
}

相关问题