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 
}
相关推荐
2601_9498333914 小时前
flutter_for_openharmony口腔护理app实战+意见反馈实现
android·javascript·flutter
峥嵘life14 小时前
Android 16 EDLA测试STS模块
android·大数据·linux·学习
TheNextByte114 小时前
如何打印Android手机联系人?
android·智能手机
泡泡以安15 小时前
Android 逆向实战:从零突破某电商 App 登录接口全参数加密
android·爬虫·安卓逆向
2501_9445255416 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 预算详情页面
android·开发语言·前端·javascript·flutter·ecmascript
清蒸鳜鱼17 小时前
【Mobile Agent——Droidrun】MacOS+Android配置、使用指南
android·macos·mobileagent
2501_9159184117 小时前
HTTPS 代理失效,启用双向认证(mTLS)的 iOS 应用网络怎么抓包调试
android·网络·ios·小程序·https·uni-app·iphone
峥嵘life18 小时前
Android EDLA CTS、GTS等各项测试命令汇总
android·学习·elasticsearch
Cobboo18 小时前
i单词上架鸿蒙应用市场之路:一次从 Android 到 HarmonyOS 的完整实战
android·华为·harmonyos
天下·第二18 小时前
达梦数据库适配
android·数据库·adb