Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin For loop start from a given index

Tags:

kotlin

I want to start a For loop from a given index in Java you can easily write

for (int i = startingIndex; i < items.size(); i++) 

how to to do that in Kotlin? I know how to write a for loop in Kotlin

my example

I want to iterate over an array of strings but the start position is 3, not iterating over a Range the iteration will be over a collection of items

like image 608
tamtom Avatar asked Dec 15 '19 18:12

tamtom


People also ask

When you can iterate a string using the for statement in Kotlin?

Generally, the for loop is used to iterate through the given block of code for the specified number of times. In Kotlin, the for loop works like the forEach in C#. The for loop in Kotlin can be used to iterate through anything that provides an iterator. For example, a range, array, string, etc.


2 Answers

For iterating from the start item till the last, you can use something like this:

for (i in startingIndex until items.size) {
    //apply your logic
}
like image 189
SaadAAkash Avatar answered Sep 29 '22 14:09

SaadAAkash


Another option is to drop first n elements and use forEach from there:

val l = listOf(1, 2, 3, 4)
l.drop(1).forEach { println(it) } // prints "2, 3, 4"
like image 43
Vitali Plagov Avatar answered Sep 29 '22 14:09

Vitali Plagov