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.