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 
}
相关推荐
哲鲤1 小时前
Binder 不只是 IPC:从一次跨进程调用看懂 Android 与 AAOS 的架构演进
android
用户128139778162 小时前
Eyf半字节【3.0 版】正式发布|订单、单证、扫码三大核心模块全新重构
android
device_Any3 小时前
接口文档写着三个字段,接口返回了五个
android·java·linux
kingx33 小时前
Bugku Reverse 与 Android 题解总集:APK / native / PE / IPA
android·逆向·ctf·bugku
大尚来也3 小时前
PHP 内存溢出常见原因与优化排查步骤
android
美狐美颜SDK开放平台4 小时前
开发直播APP、电商短视频与视频社交平台时,能否共用一套美颜SDK?
android·图像处理·人工智能·音视频·直播美颜sdk
事圆则缓4 小时前
Android 中的 MQTT 协议:从设备状态推送到可靠消息处理
android
三雷科技4 小时前
Android 开发环境搭建指南
android
赵庆明老师5 小时前
Android Studio Google源代理配置
android·ide·android studio
事圆则缓6 小时前
Android 核心名词手册跟读版
android