Kotlin Array - union() Function



The Kotlin array union() function is used to accumulate distinct elements of an array and other collections (list, set, etc.) into one set. This function returns the accumulated set containing distinct elements.

The set preserves the original array's element order and iterates unique elements from the other collection at the end, according to the order of other collections

Syntax

Following is the syntax of Kotlin array union() function −

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

Parameters

This function accept other collection as a parameters.

Return value

This function returns a set containing all distinct element from both collection.

Example 1

Following is a basic example to demonstrate the use of union() function to return a set containing elements of both collections −

fun main(args: Array<String>) {
   // Define an array
   val array = arrayOf(1, 2, 3, 4, 5, 6)

   // define a list
   val list = listOf(7, 8, 9)

   // Create a set using union function
   val to_set = array.union(list);
   println("Original array: ${array.joinToString(", ")}")
   println("Original list: $list")
   println("Set: $to_set")
}

Output

The above code generate following output −

Original array: 1, 2, 3, 4, 5, 6
Original list: [7, 8, 9]
Set: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 2

Let's see another example. Here, we use the union function to return a set containing distinct elements of both collections −

fun main(args: Array<String>) {
   // Define an array
   val array = arrayOf<String>("Daisy", "Rose", "Lily", "Lotus")

   // define a list
   val list = listOf<String>("Daisy", "Sunflower", "Marigold")

   // Create a set using union function
   val to_set = array.union(list);
   println("Original array: ${array.joinToString(", ")}")
   println("Original list: $list")
   println("Set: $to_set")
}

Output

Following is the output −

Original array: Daisy, Rose, Lily, Lotus
Original list: [Daisy, Sunflower, Marigold]
Set: [Daisy, Rose, Lily, Lotus, Sunflower, Marigold]

Example 3

Let's continue with the another example to crate a set from two arrays and demonstrate how duplicates are removed −

fun main(args: Array<String>) {
   // Define an array with some duplicate elements
   val array1 = arrayOf(1, 2, 3, 4, 2, 3, 5, 6, 7, 8, 6)

   // Define another array with some duplicate elements
   val array2 = arrayOf(1, 2, 10, 11, 9, 10)

   // Convert arrays to lists and perform union
   val intSet: Set<Int> = array1.toList().union(array2.toList())

   // Display the original arrays and the resulting set
   println("Original array1: ${array1.joinToString(", ")}")
   println("Original array2: ${array2.joinToString(", ")}")
   println("Set: ${intSet.joinToString(", ")}")
}

Output

The above code produce following output −

Original array1: 1, 2, 3, 4, 2, 3, 5, 6, 7, 8, 6
Original array2: 1, 2, 10, 11, 9, 10
Set: 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 9
kotlin_arrays.htm
Advertisements