Vivek Modi
Vivek Modi

Reputation: 7151

Get Item between ranges of list kotlin

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.

Upvotes: 3

Views: 7208

Answers (2)

Sanket Zade
Sanket Zade

Reputation: 21

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]

Upvotes: 1

Madhu Bhat
Madhu Bhat

Reputation: 15173

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.

Upvotes: 10

Related Questions