如何在groovy中访问地图中的数组?

时间:2017-02-12 21:24:59

标签: groovy

我有一个包含数组的地图:fruits = [[apples, bananas, pears]:lunch, [apples, grapes]:dinner, [pears, mango, oranges]:breakfast, [mango]:snack]

我需要找到相同的重复水果并将其与相关的一餐一起输出,例如输出为apples:lunchapples:dinner

我试过flatten.()数组但没有成功:

fruits.flatten().countBy{it}.findAll {it.value > 1}.keySet()

1 个答案:

答案 0 :(得分:5)

好的,给出以下地图:

def fruits = [['apples', 'bananas', 'pears']:'lunch',
              ['apples', 'grapes']:'dinner',
              ['pears', 'mango', 'oranges']:'breakfast',
              ['mango']:'snack']

您可以获得所有密钥的列表:

fruits.keySet().flatten()

然后循环浏览,并收集每张食物的地图(将它们收集到列表中):

.collectEntries { f -> [f, fruits.findAll { it.key.contains(f) }.values().collect()] }

并且(如果你想),只保留两餐中出现的那些:

.findAll { it.value.size() > 1 }

所以把它们放在一起,

def repeatedIngredients = fruits.keySet()
      .flatten()
      .collectEntries { f -> [f, fruits.findAll { it.key.contains(f) }.values().collect()] }
      .findAll { it.value.size() > 1 }

给你:

assert repeatedIngredients == [
    'apples':['lunch', 'dinner'],
    'pears':['lunch', 'breakfast'],
    'mango':['breakfast', 'snack']
]