it-source

각 Kotlin에 대한 현재 인덱스를 가져오는 방법

criticalcode 2023. 8. 24. 22:12
반응형

각 Kotlin에 대한 현재 인덱스를 가져오는 방법

각 루프에 대해 인덱스를 가져오는 방법은 무엇입니까?매초 반복할 때마다 숫자를 인쇄합니다.

예를들면

for (value in collection) {
    if (iteration_no % 2) {
        //do something
    }
}

자바에서는 루프에 대한 전통적인 방식이 있습니다.

for (int i = 0; i < collection.length; i++)

다음을 수행하는 방법i?

@Audi에서 제공하는 솔루션 외에도 다음과 같은 기능이 있습니다.

collection.forEachIndexed { index, element ->
    // ...
}

사용하다indices

for (i in array.indices) {
    print(array[i])
}

인덱스뿐만 아니라 값도 원하는 경우 사용withIndex()

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

참조:코틀린의 제어 흐름

또는 라이브러리 기능을 사용할 수 있습니다.

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

제어 흐름: if, time, for, while: https://kotlinlang.org/docs/reference/control-flow.html

이것을 시도해 보세요; 루프를 위해.

for ((i, item) in arrayList.withIndex()) { }

작업 예제forEachIndexed안드로이드로

색인으로 반복

itemList.forEachIndexed{index, item -> 
println("index = $index, item = $item ")
}

색인을 사용하여 목록 업데이트

itemList.forEachIndexed{ index, item -> item.isSelected= position==index}

당신이 정말로 찾고 있는 것은filterIndexed

예:

listOf("a", "b", "c", "d")
    .filterIndexed { index, _ ->  index % 2 != 0 }
    .forEach { println(it) }

결과:

b
d

한 번만 시도해 보세요.

yourList?.forEachIndexed { index, data ->
     Log.d("TAG", "getIndex = " + index + "    " + data);
 }

범위는 또한 다음과 같은 상황에서 읽을 수 있는 코드로 이어집니다.

(0 until collection.size step 2)
    .map(collection::get)
    .forEach(::println)

변수를 초기화할 수 있습니다.counter=0루프 내부의 증분:

for (value in collection){//do something then count++ }`

언급URL : https://stackoverflow.com/questions/48898102/how-to-get-the-current-index-in-for-each-kotlin

반응형