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 
}
相关推荐
Android-Flutter23 分钟前
android Binder 应用层开发 详解
android·binder
文人sec14 小时前
MySQL主库出问题了,从库怎么办?备库为什么会延迟好几个小时?
android·数据库·mysql
hai_android14 小时前
不用 AIDL,手把手教你手写 Binder 代理类
android·kotlin
mmsx15 小时前
osmdroid 地图实战 03|地图的"分层世界":离线方案、图层模型与 Overlay 体系
android·前端
张文是假的啊16 小时前
IOC依赖注入问题:@Primary 和 @Qualifier的使用
android
换元不配限16 小时前
ConstraintLayout核心用法详解(三):引导线、屏障、组和占位
android·placeholder·barrier·约束布局·guideline
雨白17 小时前
Kotlin 泛型进阶:攻克型变与实化,直击痛点
kotlin
心平气和量大福大18 小时前
android studio(AS)工具-调试-统计总行数
android·ide·android studio
你的坚定19 小时前
SurfaceFlinger合成一帧的完整流程
android
爱笑鱼21 小时前
Android 系统启动机制(七):进入 SystemServer.main() 以后,system_server 还是一个空进程吗?
android·linux