Back to Blog

Kotlin with Copilot: Merge 2 lists

Sandy LaneSandy Lane

Video: Kotlin with Copilot: Merge 2 lists by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin with Copilot: Merge 2 Lists

Merging two lists in Kotlin is a common task that can be done efficiently using built-in functions. This example demonstrates how to combine two lists into one, preserving the order of elements from both lists.

Code

fun main() {
  val list1 = listOf(1, 2, 3)
  val list2 = listOf(4, 5, 6)

  // Merge two lists using the plus operator
  val mergedList = list1 + list2

  println(mergedList)  // Output: [1, 2, 3, 4, 5, 6]
}

Key Points

  • The plus operator (+) can concatenate two lists into a new list in Kotlin.
  • Original lists remain unchanged because Kotlin lists are immutable by default.
  • You can also use list1.plus(list2) as an alternative to the + operator.
  • The merged list preserves the order of elements from both input lists.
  • For mutable lists, consider using addAll() to merge in-place.