Home > database >  Get Item between ranges of list kotlin
Get Item between ranges of list kotlin

Time:10-20

Hey I have list of int type for example. I want to pass startingIndex and endingIndex to get between items of that range in list. So How can I do this in efficient way in Kotlin.

val list = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)

For example

Scenario 1

startingIndex = 2, endingIndex = 6

List will returns items

Expected Output

3, 4, 5, 6, 7

Scenario 2

startingIndex = 0, endingIndex = 2

List will returns items

1, 2, 3

Thanks in advance.

CodePudding user response:

You can use Kotlin's slice function to get a part of the list by passing the range of indices.

val list = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)

println(list.slice(2..6)) //prints [3, 4, 5, 6, 7]

println(list.slice(0..2)) //prints [1, 2, 3]

For any collection related operations, the best way to find out would be to check Kotlin's documentation for collections, as a lot of operations are supported by Kotlin's standard library by default.

  • Related