groovy 穿越这个阵列的最佳方式?

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

我得到了这个数组:

[
  [TYPE: house, NAME: john],
  [TYPE: apartment, NAME: bob],
  [TYPE: condo, NAME: jack],
  [TYPE: bungalo, NAME: jill],
  [TYPE: box, NAME: tim]
]

我需要NAME,其中TYPE是condo...但它不是一个Map或字典,这可能是,所以最理想的,我必须迭代每个元素,并检查是否TYPE = condo,以获得我想要的名称?
谢谢你,谢谢你

ryoqjall

ryoqjall1#

因为这不是索引数据,所以您需要遍历列表以找到您想要的内容:

def array = [
  [TYPE: house, NAME: john],
  [TYPE: apartment, NAME: bob],
  [TYPE: condo, NAME: jack],
  [TYPE: bungalo, NAME: jill],
  [TYPE: box, NAME: tim]
]

def result = array.find { it.TYPE == condo }
if (result) {
  println "Found condo: $result"
} else {
  println 'No condo'
}

如果您要执行许多类似的查询,您可能会想要先索引数据一次,这样查询会更有效率:

def indexedData = array.groupBy { it.TYPE }

// now it's very efficient to find the condo
// but it may have more than one so the values are Lists
def theCondo = indexedData[condo]

if (theCondo) {
  println "The condo again: ${theCondo.first()}"
} else {
  println 'No condo yet'
}

DEMO

相关问题