Kotlin distinct用法及代码示例

本文方法及代码示例基于Kotlin 2.1.20 Released

distinct 所在包 kotlin.collections.distinct,其相关用法介绍如下:

用法一

kotlin 复制代码
fun <T> Array<out T>.distinct(): List<T>

返回仅包含给定数组中不同元素的列表。

在给定数组的相等元素中,只有第一个元素会出现在结果列表中。结果列表中的元素与它们在源数组中的顺序相同。

用法二

kotlin 复制代码
fun ByteArray.distinct(): List<Byte>

fun ShortArray.distinct(): List<Short>

fun IntArray.distinct(): List<Int>

fun LongArray.distinct(): List<Long>

fun FloatArray.distinct(): List<Float>

fun DoubleArray.distinct(): List<Double>

fun BooleanArray.distinct(): List<Boolean>

fun CharArray.distinct(): List<Char>

返回仅包含给定数组中不同元素的列表。

结果列表中的元素与它们在源数组中的顺序相同。

用法三

kotlin 复制代码
fun <T> Iterable<T>.distinct(): List<T>

返回仅包含给定集合中不同元素的列表。

在给定集合的相同元素中,只有第一个元素会出现在结果列表中。结果列表中的元素与它们在源集合中的顺序相同。

示例代码:

kotlin 复制代码
import kotlin.test.* 

fun main(args: Array<String>) { 
//sampleStart 
val list = listOf('a', 'A', 'b', 'B', 'A', 'a') 
println(list.distinct()) // [a, A, b, B] 

println(list.distinctBy { it.uppercaseChar() }) // [a, b] 
//sampleEnd 
}
相关推荐
威哥爱编程44 分钟前
谷歌Android闭源与鸿蒙崛起:一场关于技术主权的生态博弈
android·harmonyos
小鱼人爱编程2 小时前
Flutter 打包APK的几种方式
android·前端·后端
sunly_2 小时前
Flutter:切换账号功能记录
android·java·flutter
好_快3 小时前
Lodash源码阅读-baseIsEqualDeep
前端·javascript·源码阅读
好_快3 小时前
Lodash源码阅读-assignValue
前端·javascript·源码阅读
好_快3 小时前
Lodash源码阅读-copyArray
前端·javascript·源码阅读
好_快3 小时前
Lodash源码阅读-initCloneObject
前端·javascript·源码阅读
好_快3 小时前
Lodash源码阅读-baseCreate
前端·javascript·源码阅读
casual_clover4 小时前
Android 设备实现 adb connect 连接的步骤
android·adb
恋猫de小郭4 小时前
Android 确定废弃「屏幕方向锁定」等 API ,如何让 App 适配大屏和 PC/XR 等场景
android·前端·flutter