- Kotlin 教程
- Kotlin - 首页
- Kotlin - 概述
- Kotlin - 环境搭建
- Kotlin - 架构
- Kotlin - 基本语法
- Kotlin - 注释
- Kotlin - 关键字
- Kotlin - 变量
- Kotlin - 数据类型
- Kotlin - 运算符
- Kotlin - 布尔值
- Kotlin - 字符串
- Kotlin - 数组
- Kotlin - 范围
- Kotlin - 函数
- Kotlin 控制流
- Kotlin - 控制流
- Kotlin - if...else 表达式
- Kotlin - when 表达式
- Kotlin - for 循环
- Kotlin - while 循环
- Kotlin - break 和 continue
- Kotlin 集合
- Kotlin - 集合
- Kotlin - 列表
- Kotlin - 集合
- Kotlin - 映射
- Kotlin 对象和类
- Kotlin - 类和对象
- Kotlin - 构造函数
- Kotlin - 继承
- Kotlin - 抽象类
- Kotlin - 接口
- Kotlin - 可见性控制
- Kotlin - 扩展
- Kotlin - 数据类
- Kotlin - 密封类
- Kotlin - 泛型
- Kotlin - 委托
- Kotlin - 解构声明
- Kotlin - 异常处理
- Kotlin 有用资源
- Kotlin - 快速指南
- Kotlin - 有用资源
- Kotlin - 讨论
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
广告