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 
}
相关推荐
雨白21 分钟前
Jetpack系列(四):精通WorkManager,让后台任务不再失控
android·android jetpack
mmoyula2 小时前
【RK3568 驱动开发:实现一个最基础的网络设备】
android·linux·驱动开发
sam.li3 小时前
WebView安全实现(一)
android·安全·webview
移动开发者1号4 小时前
Kotlin协程超时控制:深入理解withTimeout与withTimeoutOrNull
android·kotlin
程序员JerrySUN4 小时前
RK3588 Android SDK 实战全解析 —— 架构、原理与开发关键点
android·架构
移动开发者1号4 小时前
Java Phaser:分阶段任务控制的终极武器
android·kotlin
哲科软件13 小时前
跨平台开发的抉择:Flutter vs 原生安卓(Kotlin)的优劣对比与选型建议
android·flutter·kotlin
jyan_敬言19 小时前
【C++】string类(二)相关接口介绍及其使用
android·开发语言·c++·青少年编程·visual studio
程序员老刘19 小时前
Android 16开发者全解读
android·flutter·客户端
福柯柯20 小时前
Android ContentProvider的使用
android·contenprovider