Kotlin distinctBy用法及代码示例

本文方法及代码示例基于Kotlin 2.1.20 Released

distinctBy 所在包 kotlin.collections.distinctBy,其相关用法介绍如下:

用法一

kotlin 复制代码
inline fun <T, K> Array<out T>.distinctBy(     
    selector: (T) -> K 
): List<T>

返回一个列表,该列表仅包含给定数组中具有给定 selector 函数返回的不同键的元素。

在给定数组的具有相同键的元素中,只有第一个元素会出现在结果列表中。结果列表中的元素与它们在源数组中的顺序相同。

用法二

kotlin 复制代码
inline fun <K> ByteArray.distinctBy(
    selector: (Byte) -> K
): List<Byte>

inline fun <K> ShortArray.distinctBy(
    selector: (Short) -> K
): List<Short>

inline fun <K> IntArray.distinctBy(
    selector: (Int) -> K
): List<Int>

inline fun <K> LongArray.distinctBy(
    selector: (Long) -> K
): List<Long>

inline fun <K> FloatArray.distinctBy(
    selector: (Float) -> K
): List<Float>

inline fun <K> DoubleArray.distinctBy(
    selector: (Double) -> K
): List<Double>

inline fun <K> BooleanArray.distinctBy(
    selector: (Boolean) -> K
): List<Boolean>

inline fun <K> CharArray.distinctBy(
    selector: (Char) -> K
): List<Char>

返回一个列表,该列表仅包含给定数组中具有给定 selector 函数返回的不同键的元素。

结果列表中的元素与它们在源数组中的顺序相同。

用法三

kotlin 复制代码
inline fun <T, K> Iterable<T>.distinctBy(     
    selector: (T) -> K 
): List<T>

返回一个列表,该列表仅包含给定数组中具有给定 selector 函数返回的不同键的元素。

在给定集合的具有相同键的元素中,只有第一个元素会出现在结果列表中。结果列表中的元素与它们在源集合中的顺序相同。

示例代码:

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 
}
相关推荐
贺biubiu3 小时前
2025 年终总结|总有那么一个人,会让你千里奔赴...
android·程序员·年终总结
xuekai200809013 小时前
mysql-组复制 -8.4.7 主从搭建
android·adb
资生算法程序员_畅想家_剑魔4 小时前
Kotlin常见技术分享-02-相对于Java 的核心优势-协程
java·开发语言·kotlin
nono牛4 小时前
ps -A|grep gate
android
未知名Android用户5 小时前
Android动态变化渐变背景
android
nono牛6 小时前
Gatekeeper 的精确定义
android
stevenzqzq8 小时前
android启动初始化和注入理解3
android
城东米粉儿10 小时前
compose 状态提升 笔记
android
粤M温同学10 小时前
Android 实现沉浸式状态栏
android
ljt272496066110 小时前
Compose笔记(六十八)--MutableStateFlow
android·笔记·android jetpack