Kotlin Array - subtract() Function



The Kotlin array subtract() function is used to subtract element of an array from another collection and return a set containing elements in this array but not in the specified collection ("list", and "set").

The returned set preserves the element iteration order of the original array.

Syntax

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

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

Parameters

This function accepts other collection (elements) as a parameter. Which represent an Iterable containing the elements to be subtracted from the array. It can be any collection like List, Set, etc.

Return value

This function returns a Set containing elements of the original array that are not present in the specified collection (elements).

Example 1

Following is a basic example to demonstrate the use of subtract() function −

fun main() {
   val array = arrayOf(1, 2, 3, 4, 5)
   val elementsToSubtract = listOf(2, 4)

   // Subtract elementsToSubtract from array
   val result = array.subtract(elementsToSubtract)

   // Display result
   println(result)
}

Output

The above code generate following output −

[1, 3, 5]

Example 2

Now, we create an array of string. We then use subtract() function to subtract the list from an array −

fun main(args: Array<String>){
   val arr = arrayOf<String>("Daisy", "Rose", "Lotus", "Lily", "Sunflower")
   
   // elements to subtract 
   val list = listOf("Lotus", "Lily")
   
   // subtract list from this array
   val res = arr.subtract(list)
   println("After subtracted: $res")
}

Output

Following is the output −

After subtracted: [Daisy, Rose, Sunflower]

Example 3

The below example creates an array of objects representing employees, and we want to remove a subset of employees based on their IDs using the subtract() function −

data class Employee(val id: Int, val name: String, val department: String)
fun main() {
   val employees = arrayOf(
      Employee(1, "Alice", "HR"),
      Employee(2, "Bob", "Engineering"),
      Employee(3, "Charlie", "Finance"),
      Employee(4, "Diana", "Engineering"),
      Employee(5, "Eve", "HR")
   )

   val ids_To_Remove = setOf(2, 4)

   // Convert the set of IDs to remove into a list of employees to remove
   val employees_To_Remove = employees.filter { it.id in ids_To_Remove }

   // Subtract the employees to remove from the original array
   val remainingEmployees = employees.subtract(employees_To_Remove)

   // Display remaining employees
   remainingEmployees.forEach { println("${it.id}: ${it.name} - ${it.department}") }
}

Output

The above code produce following output −

1: Alice - HR
3: Charlie - Finance
5: Eve - HR
kotlin_arrays.htm
Advertisements