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 
}
相关推荐
xiangpanf20 小时前
Laravel 10.x重磅升级:五大核心特性解析
android
robotx1 天前
安卓线程相关
android
消失的旧时光-19431 天前
Android 面试高频:JSON 文件、大数据存储与断电安全(从原理到工程实践)
android·面试·json
dalancon1 天前
VSYNC 信号流程分析 (Android 14)
android
dalancon1 天前
VSYNC 信号完整流程2
android
dalancon1 天前
SurfaceFlinger 上帧后 releaseBuffer 完整流程分析
android
用户69371750013841 天前
不卷AI速度,我卷自己的从容——北京程序员手记
android·前端·人工智能
程序员Android1 天前
Android 刷新一帧流程trace拆解
android
墨狂之逸才1 天前
解决 Android/Gradle 编译报错:Comparison method violates its general contract!
android
阿明的小蝴蝶1 天前
记一次Gradle环境的编译问题与解决
android·前端·gradle