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 
}
相关推荐
YF02117 小时前
Flutter 编译卡顿解决方案
android·flutter·ios
空中海8 小时前
第十二章:安卓实战架构与最佳实践
android·架构
雨白10 小时前
深入理解 Kotlin 协程 (五):偷天换日,探秘状态机与调度的运转引擎
kotlin
angerdream10 小时前
Android手把手编写儿童手机远程监控App之四大组件详解2
android
kerli10 小时前
基于 kmp/cmp 的跨平台图片加载方案 - 适配 Android View/Compose/ios
android·前端·ios
半条-咸鱼11 小时前
基于安卓的 WAV 音频采集方案_含工具
android·音视频
九皇叔叔11 小时前
MySQL8.0 版本安装部署
android·adb
OneLIMS12 小时前
OneLIMS 安卓 APK 一键打包说明文档
android
阿亮爱学代码15 小时前
初识Android界面布局
android·xml·view·viewgroup