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 
}
相关推荐
Lei活在当下3 分钟前
【Perfetto从入门到精通】4.使用 heapprofd 工具采样追踪 Java/Native 内存分配
android·性能优化·架构
alexhilton1 小时前
学会在Jetpack Compose中加载Lottie动画资源
android·kotlin·android jetpack
summerkissyou19872 小时前
Android-Camera-为啥不移到packages/module
android·相机
liang_jy2 小时前
Android UID
android·面试
nono牛5 小时前
安卓/MTK平台日志关键词详解
android
TimeFine6 小时前
Android AI解放生产力(四)实战:解放绘制UI的繁琐工作
android
sheji34166 小时前
【开题答辩全过程】以 基于Android的社区车位共享管理系统的设计与实现为例,包含答辩的问题和答案
android
TimeFine7 小时前
Android AI解放生产力(三):认识custom_prompts和skills
android
summerkissyou19877 小时前
Android-Audio-为啥不移到packages/module
android·音视频
catchadmin7 小时前
PHP 值对象实战指南:避免原始类型偏执
android·开发语言·php