Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Sets

Set data structure is used to store multiple items of same data type where duplicates are not allowed & order of elements is not maintained.

Basic operations

Following is the syntax for working with sets :

 // Creating an empty Set
emptySet</* Type */>()

// Creating a (immutable) set of elements
setOf(/* Elements */)

// Creating a MutableSet of elements
mutableSetOf(/* Elements */)

// Create a set from list or array
list/array.toSet()

// Create a MutableSet from list or array
list/array.toMutableSet()

// Printing a set
println(set)

// Check if an element exists in set
set.contains(/* element */)

// Adding an element to set
set.add(/* element */)

// Removing an element from set
set.remove(/* element */)
 

Note that set does not have index based operations because order is not mainatained in a set.

Set operations

Recall from mathematics that following operations can be performed on a set :

Similarly, we can perform these operations on sets using predefined functions :

 // Union
setA.union(setB) /* OR */ setA union setB

// Intersect
setA.intersect(setB) /* OR */ setA intersect setB

// Difference
setA.subtract(setB) /* OR */ setA subtract setB
 

Example :

 fun main() {
		val a = setOf(1, 2, 3)
		val b = setOf(3, 4, 5)
		println("a ∪ b = ${a union b}")
		println("a - b = ${a subtract b}")
		println("a ∩ b = ${a intersect b}")
}

/* Output :
a ∪ b = [1, 2, 3, 4, 5]
a - b = [1, 2]
a ∩ b = [3] */
 

💡 Wondering How?
How are we able to call union function without . and ()? Because this is an example of infix function. When calling infix functions, we can remove . and ()!