Back to Blog

Kotlin: Remove last items from list and array

Sandy LaneSandy Lane

Video: Kotlin: Remove last items from list and array by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin: Remove Last Items from List and Array

In Kotlin, you can easily remove the last elements from a list or an array using built-in functions and extension methods. This example demonstrates how to remove the last item or multiple items from both mutable lists and arrays, showcasing idiomatic Kotlin techniques.

Code

fun main() {
  // Removing last item from a mutable list
  val mutableList = mutableListOf("apple", "banana", "cherry", "date")
  if (mutableList.isNotEmpty()) {
    mutableList.removeAt(mutableList.size - 1)  // Removes "date"
  }
  println(mutableList)  // Output: [apple, banana, cherry]

  // Removing last N items from a mutable list
  val n = 2
  if (mutableList.size >= n) {
    repeat(n) { mutableList.removeAt(mutableList.size - 1) }
  }
  println(mutableList)  // Output: [apple]

  // Removing last item from an array by creating a new array
  val array = arrayOf(1, 2, 3, 4, 5)
  val newArray = array.copyOf(array.size - 1)  // Removes last element (5)
  println(newArray.joinToString())  // Output: 1, 2, 3, 4

  // Removing last N items from an array using sliceArray
  val nItems = 3
  val slicedArray = array.sliceArray(0 until array.size - nItems)
  println(slicedArray.joinToString())  // Output: 1, 2
}

Key Points

  • Mutable lists allow removing elements in-place using removeAt with the last index.
  • To remove multiple last items from a list, repeat removeAt calls or use subList if preferred.
  • Arrays are fixed size, so removing items involves creating a new array with copyOf or sliceArray.
  • sliceArray provides a concise way to get a subarray excluding the last N elements.
  • Always check list or array size before removing elements to avoid exceptions.