Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract pairs from list in Groovy

Tags:

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?

like image 900
Michal Kordas Avatar asked Dec 29 '25 00:12

Michal Kordas


1 Answers

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

like image 53
tim_yates Avatar answered Dec 31 '25 00:12

tim_yates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!