Reputation: 227
I have two lists that look like this:
def justNames = ["test", "test1"]
def namesWithNumber = ["test-1", "test-2", "test1-2"]
I want to create a list of pairs such that each pair has one element from justNames and one element from namesWithNumber under the following condition. The element from justNames must be an exact match for the part of the element from namesWithNumber that comes before the hyphen. So:
def pairs = [["test", "test-1"], ["test1", "test1-2"], ["test", "test-2"]]
I'm having trouble figuring out what the best way to loop through the lists will be. In my actual code, justNames is quite large and namesWithNumber is much smaller. Can anyone suggest a groovy way to create the list of pairs? If it matters or helps, justNames and namesWithNumber were created from a single list using a regular expression like this:
def testList = ["test", "test-1", "test1", "test-2", "test1-2"]
def justNames = []
def namesWithNumber = []
testList.each {
if (it =~ /-\d$/) {
namesWithNumber << it
} else {
justNames << it
}
}
Thanks!
Upvotes: 1
Views: 825
Reputation: 50285
[justNames, namesWithNumber].combinations().findAll{it[0] == it[1].split(/-/)[0]}
Upvotes: 2