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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With