'Groovy - cartesian product of two lists

I have two list and I want to create list which will be cartesian product of them.

def repoNames = ["repo1", "repo2"]
def environments = ["env1", "env2"]

def data = repoNames.collect { repoName ->
    environments.collect { environment ->
        [environment, repoName]    
    }
}

​println data

What I get eventually is list inside list

[[[env1, repo1], [env2, repo1]], [[env1, repo2], [env2, repo2]]]

What I need is this

[[env1, repo1], [env2, repo1], [env1, repo2], [env2, repo2]]


Solution 1:[1]

What I need is this

[[env1, repo1], [env2, repo1], [env1, repo2], [env2, repo2]]

There are many ways to do it. This is one.

def repoNames = ["repo1", "repo2"]
def environments = ["env1", "env2"]

def data = []
repoNames.each { repoName ->
    environments.each { envName ->
        data << [envName, repoName]
    }
}

You could also do something like this:

def repoNames = ["repo1", "repo2"]
def environments = ["env1", "env2"]

def data = repoNames.stream().flatMap { repoName ->
    environments.stream().map { envName ->
        [envName, repoName]
    }
}.collect(java.util.stream.Collectors.toList())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1