Kotlin distinctBy用法及代码示例

39 阅读1分钟

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

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

用法一

inline fun <T, K> Array<out T>.distinctBy(     
    selector: (T) -> K 
): List<T>

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

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

用法二

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 函数返回的不同键的元素。

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

用法三

inline fun <T, K> Iterable<T>.distinctBy(     
    selector: (T) -> K 
): List<T>

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

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

示例代码:

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 
}

相关用法