Kotlin: Merge 2 lists
Video: Kotlin: Merge 2 lists by Taught by Celeste AI - AI Coding Coach
Watch full page →Kotlin: Merge 2 Lists
Merging two lists in Kotlin is a common operation that can be done efficiently using built-in functions. Whether you want to combine lists into a new one or append elements, Kotlin provides clear and concise methods to achieve this.
Code
fun main() {
val list1 = listOf(1, 2, 3)
val list2 = listOf(4, 5, 6)
// Merge two lists into a new list using the plus operator
val mergedList = list1 + list2
println("Merged list: $mergedList")
// Alternatively, use the plus function explicitly
val mergedList2 = list1.plus(list2)
println("Merged list 2: $mergedList2")
// If you want a mutable list, you can convert and addAll
val mutableList = list1.toMutableList()
mutableList.addAll(list2)
println("Mutable merged list: $mutableList")
}
Key Points
- The plus operator (+) combines two lists into a new list without modifying the originals.
- The plus() function is an explicit alternative to the + operator for merging lists.
- To modify a list by adding elements, convert it to a MutableList and use addAll().
- Original lists remain unchanged when merging with + or plus(), ensuring immutability.