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 
}
相关推荐
xzkyd outpaper2 小时前
onSaveInstanceState() 和 ViewModel 在数据保存能力差异
android·计算机八股
梓仁沐白3 小时前
【Kotlin】协程
开发语言·python·kotlin
CYRUS STUDIO3 小时前
FART 脱壳某大厂 App + CodeItem 修复 dex + 反编译还原源码
android·安全·逆向·app加固·fart·脱壳
WAsbry3 小时前
现代 Android 开发自定义主题实战指南
android·kotlin·material design
xzkyd outpaper4 小时前
Android动态广播注册收发原理
android·计算机八股
唐墨1234 小时前
android与Qt类比
android·开发语言·qt
林林要一直努力5 小时前
Android Studio 向模拟器手机添加照片、视频、音乐
android·智能手机·android studio
AD钙奶-lalala5 小时前
Mac版本Android Studio配置LeetCode插件
android·ide·android studio
梓仁沐白6 小时前
【Kotlin】注解&反射&扩展
开发语言·python·kotlin
散人10246 小时前
Android Test3 获取的ANDROID_ID值不同
android·unit testing