Kotlin - Functionally Traverse Collection getting current/next value

Viewed 96

In Kotlin, is there a functional way to traverse through a List<T> getting a Pair<T,T> that reflect the current/next element.

E.g. - the imperative approach would be something like

for (index in 0 until list.size-1) {
        val current = list[index]
        val next = list[index + 1]
        //do calculations on current/next.
    }

Something like list.forEachPaired { it: Pair<String,String?> ->//do something }

3 Answers

windowed (see link for the parameters). If you want to work with Pairs in particular, you can use the overload with transform:

list.windowed(2) { Pair(it[0], it[1]) }.forEach { ... }

but I'd just write

list.windowed(2).forEach { ... }

where the parameter of forEach's lambda is a List<T> of length 2.

Although windowed() is powerful, there's a slightly simpler alternative in this case: zipWithNext(). For example:

list.zipWithNext().forEach{ (first, second) ->
    // ...
}

I agree with Alexey Romanov that the intermediate Pairs are not necessary really. You can destructure your windowed lists in a forEach lambda:

list.windowed(2).forEach { (first, second) ->

}
Related