3

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.

Kotlin Learner
  • 3,995
  • 6
  • 47
  • 127

2 Answers2

9

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.

Madhu Bhat
  • 13,559
  • 2
  • 38
  • 54
1

Here you can use List.subList(a, b) method. It takes two parameters, starting and ending index.

val list = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13)
println(list.subList(0,4)) //prints [1, 2, 3,4]
helvete
  • 2,455
  • 13
  • 33
  • 37