Home > Enterprise >  Kotlin: How to iterate over the list from specific index?
Kotlin: How to iterate over the list from specific index?

Time:08-30

I want to dynamically iterate over the list from specific index with dynamic end of the iteration.

Example: If I have List and there are 8 elements in it(thats static it will always be 8) and I pass index 5, I want to iterate that list from index 5 to index 5 (5 6 7 0 1 2 3 4).

CodePudding user response:

Use remainder as index

val list = listOf(0, 1, 2, 3, 4, 5, 6, 7)
val offset = 5
for (ix in list.indices) {
    println(list[(ix   offset) % list.size]) // <- starts at 0 when ix   offset is greater then size of the list
}

CodePudding user response:

You may shift items by the desired offset

Collections.rotate(list, -5)

And then iterate

  • Related