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 
}
相关推荐
aqi00几秒前
FFmpeg开发笔记(八十三)国产的视频裁剪框架AndroidVideoTrimmer
android·ffmpeg·音视频·流媒体
困到晕阙40 分钟前
[Zer0pts2020]Can you guess it?
android
写点啥呢43 分钟前
android取消每次u盘插入创建无用(媒体)文件夹
android·u盘·车机·aosp
杨筱毅1 小时前
【Android】RecyclerView LayoutManager 重写方法详解
android
shaominjin1231 小时前
Android 中 Padding 与 Margin 的深度解析:从概念到实战区分
android
2501_9151063210 小时前
iOS 26 APP 性能测试实战攻略:多工具组合辅助方案
android·macos·ios·小程序·uni-app·cocoa·iphone
怪兽201412 小时前
IntentService 的应用场景和使用方式?
android·面试
Jeled13 小时前
云信im在Android中的使用2
android
Jerry14 小时前
Compose 自定义布局和图形
android
杨筱毅14 小时前
【Android】【底层机制】组件生命周期以及背后的状态管理
android·底层机制