1

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!

1 Answer 1

2
[justNames, namesWithNumber].combinations().findAll{it[0] == it[1].split(/-/)[0]}
Sign up to request clarification or add additional context in comments.

3 Comments

I like the combinations method - saves lots of work and makes the code much cleaner
Very similar alternative [justNames, namesWithNumber].combinations().findAll{ a, b -> a == b.takeWhile { it != '-' } }
Wow, both of those suggestions are very cool and much appreciated. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.