Michal Kordas Michal Kordas - 2 months ago 10
Groovy Question

Extract pairs from list in Groovy

I need to extract pairs of surrounding elements from list in Groovy, so that the assertion passes:

assert pairs([1, 2, 3, 4]) == [[1, 2], [2, 3], [3, 4]]

def pairs(List list) {
//...
}


My current implementation is as follows:

def pairs(List list) {
def result = []
for (int i = 0; i < list.size() - 1; i++) {
result += [[list[i], list[i + 1]]]
}
result
}


Is there any more functional or groovy-way solution for that problem?

Answer

Just do:

def pairs(List list) {
    list.collate(2, 1, false)
}

THat means "group them in groups of 2, sliding along the input list 1 entry each time, and drop any groups smaller than 2" And you'll get the expected result... No need for dropping or merging or adding

Comments