English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Program to Connect and Merge Two Lists

Kotlin Comprehensive Examples

In this program, you will learn different techniques to connect two lists in Kotlin.

Example1: Use addAll() to connect and merge two lists

import java.util.ArrayList
fun main(args: Array<String>) {
    val list1 = ArrayList<String>()
    list1.add("a")
    val list2 = ArrayList<String>()
    list2.add("b")
    val joined = ArrayList<String>()
    joined.addAll(list1)
    joined.addAll(list2)
    println("list"1: $list1)
    println("list"2: $list2)
    println("joined: $joined")
}

When running the program, the output is:

list1: [a]
list2: [b]
joined: [a, b]

In the above program, we use the addAll() method of List to connect the list list1And list2List.

Example2: Use union() to connect two lists

import java.util.ArrayList;
import org.apache.commons.collections.ListUtils;
fun main(args: Array<String>) {
    val list1 = ArrayList<String>()
    list1.add("a")
    val list2 = ArrayList<String>()
    list2.add("b")
    val joined = ListUtils.union(list1, $list2)
    println("list"1: $list1)
    println("list"2: $list2)
    println("joined: $joined")
}

The output of the program is the same.

In the above program, we use the union() method to connect the given list to joined.

The following is the equivalent Java code:Java Program to Connect Two Lists.

Kotlin Comprehensive Examples