Kotlin 陣列 - distinctBy() 函式



Kotlin 陣列 distinctBy() 函式用於從給定陣列中,使用選擇器函式檢索包含不同元素的列表。結果列表中的元素順序與其在源陣列中的順序相同。

如果給定陣列中存在多個相似的元素或大小寫相同的元素,則結果列表中只包含第一次出現的元素。例如,如果陣列是 ['a', 'A', 'b', 'B'],則 distinctBy 將輸出 [a, b]。

語法

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

fun <T, K> Array<out T>.distinctBy(selector: (T) -> K): List<T>

引數

此函式接受選擇器作為引數。

返回值

此函式返回一個僅包含 distinctBy 元素的列表。

示例 1

在下面的基本示例中,我們使用 distinctBy() 函式從字串陣列中選擇元素,其區分基於起始字元:

fun main(args: Array<String>) {
   var array = arrayOf("apple", "banana", "mango", "berry", "mantos", "guava")
   var result = array.distinctBy { it[0] }
   println(result)
}

輸出

以下是輸出:

[apple, banana, mango, guava]

示例 2

現在,讓我們來看另一個例子,我們從一個字元陣列中選擇元素,其區分基於大小寫:

fun main(args: Array<String>) {
   val char = arrayOf('a', 'A', 'b', 'B', 'A', 'a', 'b')
   
   //here distinct is not checking the upper and lower case.
   val res1 = char.distinct()
   println("use of distinct function $res1")
   
   //here distinctBy is checking the upper and lower case both
   val res2 = char.distinctBy { it.uppercase() }
   println("use of distinctBy function $res2")
}

輸出

以下是輸出:

use of distinct function [a, A, b, B]
use of distinctBy function [a, b]

示例 3

下面的示例計算陣列中不同元素的和:

fun main(){
    var sum:Int =0
    var add = arrayOf<Int>(1,2,3,1,2).distinctBy { it }
    for (i in 0 until  add.size){
       sum = sum + add[i]
    }
    println("sum of all distinct element is: $sum")
}

輸出

以下是輸出:

sum of all distinct element is: 6
kotlin_arrays.htm
廣告
© . All rights reserved.