Extract a Sublist from ArrayList in Kotlin | Kotlin ArrayList subList Function

The subList function in Kotlin is used to obtain a view of a portion of an ArrayList. This function is part of the Kotlin standard library and provides a convenient way to work with a subset of a list without creating a new list.

Table of Contents

  1. Introduction
  2. subList Function Syntax
  3. Understanding subList
  4. Examples
    • Basic Usage
    • Modifying Elements in a Sublist
    • Handling IndexOutOfBoundsException
  5. Real-World Use Case
  6. Conclusion

Introduction

The subList function allows you to obtain a view of a portion of an ArrayList between a specified range of indices. This is useful for scenarios where you need to work with a subset of the list without copying the elements to a new list.

subList Function Syntax

The syntax for the subList function is as follows:

fun <T> ArrayList<T>.subList(fromIndex: Int, toIndex: Int): List<T>

Parameters:

  • fromIndex: The start index (inclusive) of the sublist.
  • toIndex: The end index (exclusive) of the sublist.

Returns:

  • List<T>: A view of the specified range within the list.

Understanding subList

The subList function returns a view of the portion of the ArrayList between the specified fromIndex, inclusive, and toIndex, exclusive. The returned list is backed by the original list, meaning changes to the sublist are reflected in the original list, and vice versa.

Examples

Basic Usage

To demonstrate the basic usage of subList, we will create an ArrayList and obtain a sublist of it.

Example

fun main() {
    val numbers = arrayListOf(10, 20, 30, 40, 50)
    val subList = numbers.subList(1, 4)
    println("Original list: $numbers")
    println("Sublist: $subList")
}

Output:

Original list: [10, 20, 30, 40, 50]
Sublist: [20, 30, 40]

Modifying Elements in a Sublist

This example shows how modifications to the sublist are reflected in the original list.

Example

fun main() {
    val fruits = arrayListOf("Apple", "Banana", "Cherry", "Date", "Elderberry")
    val subList = fruits.subList(1, 4)
    println("Original list: $fruits")
    println("Sublist before modification: $subList")

    subList[0] = "Blueberry"
    println("Sublist after modification: $subList")
    println("Original list after sublist modification: $fruits")
}

Output:

Original list: [Apple, Banana, Cherry, Date, Elderberry]
Sublist before modification: [Banana, Cherry, Date]
Sublist after modification: [Blueberry, Cherry, Date]
Original list after sublist modification: [Apple, Blueberry, Cherry, Date, Elderberry]

Handling IndexOutOfBoundsException

This example demonstrates how to handle IndexOutOfBoundsException when specifying invalid indices.

Example

fun main() {
    val colors = arrayListOf("Red", "Green", "Blue")
    try {
        val subList = colors.subList(1, 5)
        println("Sublist: $subList")
    } catch (e: IndexOutOfBoundsException) {
        println("Exception: ${e.message}")
    }
}

Output:

Exception: toIndex = 5

Real-World Use Case

Paginating a List of Items

In real-world applications, the subList function can be used to paginate a list of items, allowing you to work with a subset of the list for each page.

Example

fun main() {
    val items = arrayListOf(
        "Item1", "Item2", "Item3", "Item4", "Item5",
        "Item6", "Item7", "Item8", "Item9", "Item10"
    )
    val pageSize = 3
    val pageIndex = 2 // For example, getting the 3rd page (0-based index)

    val fromIndex = pageIndex * pageSize
    val toIndex = minOf(fromIndex + pageSize, items.size)

    if (fromIndex < items.size) {
        val page = items.subList(fromIndex, toIndex)
        println("Page $pageIndex: $page")
    } else {
        println("Invalid page index")
    }
}

Output:

Page 2: [Item7, Item8, Item9]

Conclusion

The subList function in Kotlin is a powerful and flexible way to obtain a view of a portion of an ArrayList. It allows you to work with subsets of a list without copying elements to a new list, making it useful for various applications, including pagination and data manipulation. 

By understanding and using the subList function, you can effectively manage and manipulate ArrayList collections in your Kotlin applications.

Comments