Kotlin distinct用法及代码示例

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

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

用法一

kotlin 复制代码
fun <T> Array<out T>.distinct(): List<T>

返回仅包含给定数组中不同元素的列表。

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

用法二

kotlin 复制代码
fun ByteArray.distinct(): List<Byte>

fun ShortArray.distinct(): List<Short>

fun IntArray.distinct(): List<Int>

fun LongArray.distinct(): List<Long>

fun FloatArray.distinct(): List<Float>

fun DoubleArray.distinct(): List<Double>

fun BooleanArray.distinct(): List<Boolean>

fun CharArray.distinct(): List<Char>

返回仅包含给定数组中不同元素的列表。

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

用法三

kotlin 复制代码
fun <T> Iterable<T>.distinct(): List<T>

返回仅包含给定集合中不同元素的列表。

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

示例代码:

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 
}
相关推荐
冬奇Lab1 小时前
稳定性性能系列之十一——Android内存优化与OOM问题深度解决
android·性能优化
用户74589002079542 小时前
线程池
android
专注前端30年2 小时前
【PHP开发与安全防护实战】性能调优手册
android·安全·php
王正南4 小时前
安卓逆向之LSposed开发(一)
android·xposed·lsposed
YIN_尹5 小时前
【MySQL】数据类型(上)
android·mysql·adb
zh_xuan5 小时前
kotlin 类继承的语法
开发语言·kotlin
robotx6 小时前
AOSP设备节点权限添加相关
android
顾林海6 小时前
Android文件系统安全与权限控制:给应用数据上把“安全锁”
android·面试·操作系统
青莲8436 小时前
Android 动画机制完整详解
android·前端·面试