Kotlin 陣列 - subtract() 函式



Kotlin 陣列的 subtract() 函式用於從另一個集合(“列表”和“集合”)中減去陣列的元素,並返回一個包含此陣列中但不在指定集合中的元素的集合。

返回的集合保留了原始陣列的元素迭代順序。

語法

以下是 Kotlin 陣列 subtract() 函式的語法:

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

引數

此函式接受其他集合(元素)作為引數。它表示一個包含要從陣列中減去的元素的可迭代物件。它可以是任何集合,例如列表、集合等。

返回值

此函式返回一個集合,其中包含原始陣列中不在指定集合(元素)中的元素。

示例 1

以下是一個基本的示例,用於演示 subtract() 函式的使用:

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)
}

輸出

以上程式碼生成以下輸出:

[1, 3, 5]

示例 2

現在,我們建立一個字串陣列。然後,我們使用subtract()函式從陣列中減去列表:

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")
}

輸出

以下是輸出:

After subtracted: [Daisy, Rose, Sunflower]

示例 3

下面的示例建立一個表示員工的物件陣列,我們希望使用subtract()函式根據員工 ID 刪除一部分員工:

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}") }
}

輸出

以上程式碼產生以下輸出:

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