Kotlin List union()
Syntax & Examples


Syntax of List.union()

The syntax of List.union() extension function is:

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

This union() extension function of List returns a set containing all distinct elements from both collections.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing the integers 1, 2, 3, 4, 5.
  • We create another list named list2 containing the integers 4, 5, 6, 7, 8.
  • We perform the union operation on list1 and list2 using the union() extension function, which returns a set containing all distinct elements from both lists.
  • We print the elements of the resulting set resultSet joined into a string to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(1, 2, 3, 4, 5)
    val list2 = listOf(4, 5, 6, 7, 8)
    val resultSet = list1.union(list2)
    println(resultSet.joinToString())
}

Output

1, 2, 3, 4, 5, 6, 7, 8

2 Example

In this example,

  • We create a list named list1 containing characters 'a', 'b', 'c', 'd'.
  • We create another list named list2 containing characters 'd', 'e', 'f'.
  • We perform the union operation on list1 and list2 using the union() extension function, which returns a set containing all distinct characters from both lists.
  • We print the elements of the resulting set resultSet joined into a string to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf('a', 'b', 'c', 'd')
    val list2 = listOf('d', 'e', 'f')
    val resultSet = list1.union(list2)
    println(resultSet.joinToString())
}

Output

a, b, c, d, e, f

3 Example

In this example,

  • We create a list named list1 containing strings "apple", "banana", "cherry".
  • We create another list named list2 containing strings "banana", "orange", "pear".
  • We perform the union operation on list1 and list2 using the union() extension function, which returns a set containing all distinct strings from both lists.
  • We print the elements of the resulting set resultSet joined into a string to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "banana", "cherry")
    val list2 = listOf("banana", "orange", "pear")
    val resultSet = list1.union(list2)
    println(resultSet.joinToString())
}

Output

apple, banana, cherry, orange, pear

Summary

In this Kotlin tutorial, we learned about union() extension function of List: the syntax and few working examples with output and detailed explanation for each example.