Open In App

Kotlin | Retrieve Collection Parts

Last Updated : 24 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The slice function allows you to extract a list of elements from a collection by specifying the indices of the elements you want to retrieve. The resulting list contains only the elements at the specified indices. The subList function allows you to retrieve a sublist of a collection by specifying the start and end indices of the sublist. The resulting sublist contains all the elements between the specified indices, inclusive of the start index but exclusive of the end index. We will explore both of these functions with code examples to demonstrate how to use them to retrieve collection parts in Kotlin. In Kotlin, you can retrieve parts of a collection using the slice function or the subList function. The slice function allows you to extract a list of elements from a collection by specifying the indices of the elements you want to retrieve. 

Example:

Kotlin




fun main() {
    val list = listOf("a", "b", "c", "d", "e")
    val indices = listOf(1, 3)
 
    val result1 = list.slice(indices)
    println(result1) // Output: [b, d]
 
    val result2 = list.subList(1, 4)
    println(result2) // Output: [b, c, d]
}


Output:

[b, d]
[b, c, d]

In this example, we first create a list called list containing five elements. We then create a new list called indices containing the indices of the elements we want to retrieve using the slice function.

We call the slice function on list and pass in indices as a parameter, and the resulting list is stored in the result1 variable. We then print out the contents of result1, which is [b, d].

We then use the subList function to retrieve a sublist of list containing elements from index 1 to index 4 (exclusive). The resulting sublist is stored in the result2 variable, and we print out the contents of result2, which is [b, c, d].

Kotlin provides extension functions for retrieving collection parts. A member function defined outside the class is called an extension function. These extension functions can provide a variety of ways to select different items from the list.
Four extension functions are:

  • Slice
  • Take and Drop
  • Chunked
  • Windowed

Slice

Slice functions work just like in other languages which returns a list of items with given indices. These indices can be passed as range or integer values.

Kotlin example to demonstrate slice:

Java




fun main(args : Array<String>)
{
    val fruits = listOf("apple", "banana", "cherries",
                        "dragon_fruit", "egg_fruit", "fig")
        println(fruits.slice(1..4))
            println(fruits.slice(0..4 step 2))
                println(fruits.slice(setOf(1, 2, 4)))
}


Output:

[banana, cherries, dragon_fruit, egg_fruit]
[apple, cherries, egg_fruit]
[banana, cherries, egg_fruit]

Take and Drop

As the name suggests take() function can take specified number of items from the start. If we want to grab items from last we can call takeLast() function. Similarly, drop() function takes all items except the specified number of items from the start and dropLast() takes all the items except the specified number of items from the last. 

Kotlin example to demonstrate take and drop – 

Java




fun main(args : Array<String>)
{
    val fruits = listOf("apple", "banana", "cherries",
                        "dragon_fruit", "egg_fruit", "fig")
        println(fruits.take(3)) println(fruits.takeLast(3))
            println(fruits.drop(4))
                println(fruits.dropLast(4))
}


Output:

[apple, banana, cherries]
[dragon_fruit, egg_fruit, fig]
[egg_fruit, fig]
[apple, banana]

There are four functions in take and drop with which we can use predicates to define number of items to take and drop.

Kotlin program – 

Java




fun main(args : Array<String>)
{
    val fruits = listOf("apple", "banana", "cherries",
                        "dragon_fruit", "egg_fruit", "fig")
 
        // takeWhile() takes the items upto but
        // excluding the first one not matching the
        // predicate.
        println(fruits.takeWhile{ !it.startsWith("d") })
 
        // takeLastWhile() takes a range of items
        // matching the predicate from the end.
        println(fruits.takeLastWhile{ it != "cherries" })
 
        // dropWhile() returns the items from first
        // one not matching the predicate to the end.
        println(fruits.dropWhile{ it.length == 5 })
 
        // dropWhileLast() returns element from the
        // beginning to the last one not matching the
        // predicate.
        println(fruits.dropLastWhile{ it.contains("i") })
}


Output:

[apple, banana, cherries]
[dragon_fruit, egg_fruit, fig]
[banana, cherries, dragon_fruit, egg_fruit, fig]
[apple, banana]

Chunked

Chunking is a function by which individual pieces of an list are broken down and then grouped together into specified chunk size. chunk() function takes a single argument an returns lists of that chunk size. We can also apply transformation for the returned chunks. In order to do that, we provide the transformation as a lambda function when calling chunked(). When chunked() is called with a transformation, the chunks are short-living Lists that should be used in the lambda expression for another purpose. 

Kotlin program of using chunk() function – 

Java




fun main(args : Array<String>)
{
    val fruits = listOf("apple", "banana", "cherries",
                        "dragon_fruit", "egg_fruit", "fig")
        // chunks into list size of three
        println(fruits.chunked(3))
 
        // lambda function to sum the elements
        val numbers
        = (0..11).toList()
              println(numbers.chunked(3) { it.sum() })
}


Output:

[[apple, banana, cherries], [dragon_fruit, egg_fruit, fig]]
[3, 12, 21, 30]

Windowed

The windowed() function can fetch all possible ranges of collection of items on a given size. It returns a list of element ranges that you would see at the collection using sliding window of the particular size. It has optional two parameters:
step: distance between first item of every window. By default the value is 1, so the result contains windows starting from all elements. partialWindows: if true includes windows of smaller size left at the end. 

Kotlin program to demonstrate windowed() function – 

Java




fun main(args : Array<String>)
{
    val fruits
        = listOf("apple", "banana", "cherries", "orange")
            println(fruits.windowed(3))
                println(fruits.windowed(
                    3, step = 2, partialWindows = true))
}


Output:
 

[[apple, banana, cherries], [banana, cherries, orange]]
[[apple, banana, cherries], [cherries, orange]]

There is a zipWithNext() function to build two element window, can also be called with a transformation. 

Kotlin program to demonstrate zipWithNext()

Java




fun main(args : Array<String>)
{
    val fruits = listOf("apple", "banana", "cherries",
                        "dragon_fruit", "egg_fruit", "fig")
        println(fruits.zipWithNext())
}


Output:

[(apple, banana), (banana, cherries), (cherries, dragon_fruit), 
(dragon_fruit, egg_fruit), (egg_fruit, fig)]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads