Home > other >  Kotlin: Idomatic way to get items from list after a given index
Kotlin: Idomatic way to get items from list after a given index

Time:03-27

Supposed I have a list that has 30 items and the given index is 9, I need to get the items starting index 10 to 19.

Currently doing it in a Java style.

                val newsList: ArrayList<Model> = arrayListOf()

                    // Get all items starting next to the current selected item
                    for (i in (position   1) until originalList.size) {

                        // Limit the amount of item to avoid any possible OOM
                        if (newsList.size < 10)
                            newsList.add(list[i])

                    }

CodePudding user response:

You can use drop and take for this kind of thing

val items = List(30) { i -> "Item ${i 1}"}
items.drop(10).take(10).run(::println)

>> [Item 11, Item 12, Item 13, Item 14, Item 15, Item 16, Item 17, Item 18, Item 19, Item 20]

Also you don't need to worry about how many items are in the collection - if you did drop(69) you'd just end up with an empty list. If you did listOf(1, 2).take(3) you'd just get [1, 2]. They work like "drop/take at most" - you'll only get an error if you use a negative count

  • Related