user7502743
user7502743

Reputation: 75

How do i access arrays inside a map in groovy?

I have a map which contains arrays as such: fruits = [[apples, bananas, pears]:lunch, [apples, grapes]:dinner, [pears, mango, oranges]:breakfast, [mango]:snack]

and i need to find the same repeating fruits and output them along with the associated meal, for example the output would be apples:lunch and apples:dinner

I have tried to flatten.() the array but have not succeeded:

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

Upvotes: 0

Views: 439

Answers (1)

tim_yates
tim_yates

Reputation: 171184

Ok, given the following map:

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

You can get a list of all the keys:

fruits.keySet().flatten()

Then loop through this, and collect a map of each to the meals they are found in (collecting them into a List):

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

And (if you want), only keep the ones that appear in two meals:

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

So putting it all together,

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

To give you:

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

Upvotes: 5

Related Questions