lannyf
lannyf

Reputation: 11025

kotlin, how to get sub list by its position

Having a list

val list = toList(1,2,3,4,5,6...)

would like to have a sub list from it which has only items at certain known position, i.e. position at 1, 2, 4, 7 etc.

Upvotes: 1

Views: 2237

Answers (2)

Ilya
Ilya

Reputation: 23125

You can use slice function for that providing it a list of positions:

val list = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val positions = listOf(1, 2, 4, 7)
println(list.slice(positions))

Note that it prints [2, 3, 5, 8] because positions of list items are numbered from zero in Kotlin, so the position 1 corresponds to the second element, and so on.

Upvotes: 2

IEE1394
IEE1394

Reputation: 1261

Doing it as suggested with filter Indexed

fun main() {
    val values = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
    val filter = listOf(1, 2, 4, 7)
    val resultV1 = values.filterByIndexV1(filter)
    val resultV2 = values.filterByIndexV2(filter)

    println("Input: $values")
    println("Filter: $filter")
    println("Result V1: $resultV1")
    println("Result V2: $resultV2")
}

fun <T> List<T>.filterByIndexV1(filter: List<Int>): List<T> {
    return this.filterIndexed { index, _ -> filter.contains(index) }
}

fun <T> List<T>.filterByIndexV2(filter: List<Int>): List<T> {
    return filter.map { this[it] }
}

Upvotes: 1

Related Questions