Server Side Kotlin -20

Server Side Kotlin -20


2 min read

union() function merge two collections into one. It is in the infix form a union b. Order of the operands is important. In the resulting collection, the elements of the first operand comes before the second:

val numbers = setOf("one hundred", "two hundred", "three hundred")

// output according to the order

println(numbers union setOf("four hundred", "five hundred"))

// [one, two, three, four, five]

println(setOf("four hundred", "five hundred") union numbers)

// [four, five, one, two, three]


[one hundred, two hundred, three hundred, four hundred, five hundred] [four hundred, five hundred, one hundred, two hundred, three hundred]

intersect() function find an intersection between two collections (elements present in both of them). subtract() function find collection elements not present in another collection. Both these functions can be called in the infix form as well, for example, a intersect b:

val numbers = setOf("one hundred", "two hundred ", "three hundred ")

// same output

println(numbers intersect setOf("two hundred ", "one hundred" ))

// [one, two]

println(numbers subtract setOf("three hundred", "four hundred"))

// [one, two]

println(numbers subtract setOf("four hundred", "three hundred"))

// [one, two]


[one hundred, two hundred ] [one hundred, two hundred , three hundred ] [one hundred, two hundred , three hundred ]

union() function find the elements present in either one of the two collections but not in their intersection. Operation is known as symmetric difference, and it calculate the differences between the two collections and merge the results:

val numbers = setOf("one hundred", "two hundred", "three hundred")

val numbers2 = setOf("three hundred", "four hundred")

// merge differences

println((numbers - numbers2) union (numbers2 - numbers))

// [one, two, four]


[one hundred, two hundred, four hundred]

There are also union(), intersect(), and subtract() functions to lists. However, their result is always a Set. In this result, all the duplicate elements are merged into one and the index access is not available:

val list1 = listOf(11, 11, 22, 33, 55, 88, -11)

val list2 = listOf(11, 11, 22, 22, 33, 55)

// result of intersecting two lists is a Set

println(list1 intersect list2)

//[1, 2, 3, 5]

// equal elements are merged into one

println(list1 union list2)

// [1, 2, 3, 5, 8, -1]


[11, 22, 33, 55]

[11, 22, 33, 55, 88, -11]