Kotlin Array.union()

Kotlin Array.union() Tutorial

The Array.union() function in Kotlin is used to merge two arrays into a new set containing distinct elements from both arrays. It creates a set that combines the elements of the original arrays, eliminating duplicates.

Array.union() function is useful when you need to combine arrays while ensuring that duplicate elements are removed.

This tutorial will explore the syntax of the Array.union() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.union() function is as follows:

infix fun <T> Array<out T>.union(
    other: Iterable<T>
): Set<T>

where

ParameterDescription
otherAn iterable of elements with same type as this array.
Parameters of Array.union()

Example for Array union() function

In this example, we’ll take two arrays: array1 and array2, call union() on the first array, and pass the list version of the second array. The union() function merge two arrays into a new set.

Kotlin Program

fun main() {
    val array1: Array<Int> = arrayOf(1, 2, 3, 4, 5)
    val array2: Array<Int> = arrayOf(4, 5, 6, 7, 8)

    // Using union() to merge the two arrays
    val mergedArray = array1.union(array2.toList())

    // Printing the original arrays and the resulting merged array
    println("Array 1:\n${array1.joinToString(", ")}\n")
    println("Array 2:\n${array2.joinToString(", ")}\n")
    println("Output Union Array:\n${mergedArray.joinToString(", ")}")
}

Output

Array 1:
1, 2, 3, 4, 5

Array 2:
4, 5, 6, 7, 8

Output Union Array:
1, 2, 3, 4, 5, 6, 7, 8

Summary

In this tutorial, we’ve covered the Array.union() function in Kotlin, its syntax, and how to use it to merge two arrays into a new Set with distinct elements.