Kotlin Program to Join Two Lists

Example 1: Join Two Lists using addAll()

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("list1: $list1")
    println("list2: $list2")
    println("joined: $joined")

}

When you run the program, the output will be:

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

In the above program, we used List's addAll() method to join lists list1 and list2 to the joined list.


Example 2: Join Two Lists using union()

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("list1: $list1")
    println("list2: $list2")
    println("joined: $joined")

}

The output of this program is the same.

In the above program, we used union() method to join the given lists to joined.

Here's the equivalent Java code: Java Program to join two lists.

Did you find this article helpful?