zivuska
zivuska

Reputation: 38

Combine lists that have at least one item in common

I have a list of lists in groovy. Some of the nested lists have certain items in common. I would like for all of the nested lists that have at least one item in common to join into one list, for example:

Extract of my list of lists :

[[buy, order, bought, purchase],
 [opinion, point of view],
 [opinion, belief],
 [buy, purchased],
 [buy, order, purchases]]

(The order of nested lists is random)

What I would like to achieve :

[[buy, order, bought, purchase, buy, purchased, buy, order, purchases], 
 [opinion, point of view, opinion, belief]]

Anybody has any suggestions on how to achieve this? Thank you!

Upvotes: 1

Views: 111

Answers (1)

tim_yates
tim_yates

Reputation: 171184

You can do the following with inject:

def input = [['buy', 'order', 'bought', 'purchase'],
             ['opinion', 'point of view'],
             ['opinion', 'belief'],
             ['buy', 'purchased'],
             ['buy', 'order', 'purchases']]

input.inject([]) { list, current ->
    list.find { it.intersect(current) }?.addAll(current) ?: list << current
    list
}

So, find an element in the output list that intersects with the current input list, and if it exists add it to that output list.

If one isn't found, add the input list to the output list

Upvotes: 3

Related Questions