Groovy - 两个列表的笛卡尔积

Groovy - cartesian product of two lists

我有两个列表,我想创建一个列表,它将是它们的笛卡尔积。

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

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

​println data

最终得到的是list inside list

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

我需要的是这个

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

What I need is this

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

有很多方法可以做到。这是一个。

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

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

你也可以这样做:

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())