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 
}
相关推荐
恋猫de小郭14 分钟前
Android Keep Rules 解读,直接影响 Google Play 上架和曝光
android·前端·flutter
FlightYe26 分钟前
音视频修炼之容器与协议(六):HTTP 协议
android·linux·网络·网络协议·算法·http·音视频
RobinXYuan1 小时前
【Java 字节码探秘】02 ClassFile 骨架:十个字段
java·jvm·源码阅读
StarsGreen16 小时前
Android中的seccomp相关信息介绍
android
阿杰m21 小时前
Android源码第二十四章:OTA 与 APEX——重启后换了什么?
android
用户0812680374121 小时前
差点格式化一台 Redmi K80:一次 WebView 翻车的无损救援实录
android·debug·webview
阿杰m21 小时前
Android源码第二十五章:WebView 与 Chromium——网页何时画上屏?
android·android studio
StarsGreen21 小时前
Android中特殊文件的相关说明
android
Digitally1 天前
6 款优质安卓备份提取工具与备份方案
android
恋猫de小郭1 天前
Flutter A2UI 1.0 ,原来的 genui 也正式换成了这一套 SDK 了
android·前端·flutter