Kotlin常用Collection集合操作整理

本文详细介绍了Kotlin中的常用集合操作,包括List、Set、Map的基本操作,如List转Map,Sequence的延迟计算特性,以及集合的拷贝、转换、过滤、遍历、加减、分组、取部分、排序和聚合等实用方法。通过实例展示了各种操作的用法,帮助开发者深入理解和高效使用Kotlin集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本篇记录了Kotlin常用集合的相关操作,用以熟练使用Kotlin里的相关集合。集合接口与相关函数位于kotlin.collections 包中。

常用集合

Kotlin 标准库提供了基本集合类型的实现: Set、List 以及 Map。 一对接口代表每种集合类型:

  • 一个 只读 接口,提供访问集合元素的操作
  • 一个 可变 接口,通过写操作扩展相应的只读接口:添加、删除和更新其元素

Collection集合

其中灰色是不可变集合,黄色是可变集合。Iterator意为迭代器,Collection是只读接口,而MutableCollection是一个具有写操作的Collection接口:

public interface MutableCollection<E> : Collection<E>, MutableIterable<E> {
 
    override fun iterator(): MutableIterator<E>

    public fun add(element: E): Boolean

    public fun remove(element: E): Boolean

    public fun addAll(elements: Collection<E>): Boolean

    public fun removeAll(elements: Collection<E>): Boolean

    public fun retainAll(elements: Collection<E>): Boolean

    public fun clear(): Unit
}

1.1、List

List< T> 以指定的顺序存储元素,并提供使用索引访问元素的方法。从第一个元素索引0 到最后一个元素索引(list.size - 1)为止。List 的默认实现是 ArrayList

        //不可变List,List 的默认实现是 ArrayList
        val numList = listOf("one", "two", "three")
        println(numList[0]) //one
        println(numList.get(0)) //one
        println(numList.lastIndex) //最后一个元素位置:2
        //取List一部分
        println(numList.subList(0, 2))//左边右开区间,如果越界会抛异常。执行结果:[one, two]

        //first()
        println(numList.first()) //one 取第一个元素
        println(numList.first { it.length > 3 }) //按条件取满足条件的第一个元素 都没有的话抛异常 执行结果:three
        //find() 等同于 firstOrNull()
        println(numList.firstOrNull { it.length > 5 }) //null
        println(numList.find { it.length > 5 }) //null

        //last()
        println(numList.last()) //three 取最后一个元素
        println(numList.last { it.contains("o") }) //two
        //findLast() = lastOrNull()
        println(numList.lastOrNull { it.length > 5 }) //null
        println(numList.findLast { it.length > 5 }) //null

        //index为3的位置没有元素
        println(numList.elementAtOrNull(3)) //null
        println(numList.elementAtOrElse(3) { index ->
            "The value for index $index is undefined" //The value for index 3 is undefined
        })

        println(numList.random()) //随机取一个元素

        println(numList.isEmpty())//false
        println(numList.isNotEmpty()) //true
        println(numList.isNullOrEmpty()) //false

        val initList = List(3) { it * it } //第一个参数是size,第二个参数是初始化函数
        println(initList) // [0, 1, 4]

        //List之间的比较
        val numList2 = listOf("two", "one", "three")
        println("numList==numList2:${numList == numList2}") //false  内容和元素都一致时才相等

        //可变List
        val origins = mutableListOf("one", "two", "three")
        println(origins) // 原始数据:[one, two, three]
        origins.add("three")
        println(origins) // 添加一条数据:[one, two, three, three]
        origins.removeAt(0)
        println(origins) // 删除第一条数据:[two, three, three]
        origins.remove("three")
        println(origins) // 删除符合条件的第一条element: [two, three]
        origins[0] = "newOne"
        println(origins) // 更新第一条数据:[newOne, three]
        origins.shuffle()
        println(origins) // 随机数据:[three, newOne]
        origins.removeAll { it.length == 3 }
        println(origins) //删除全部符合条件的元素 [three, newOne]
        println(origins.retainAll { it.length == 3 }) //保留全部符合条件的元素

1.1.1、List转为Map
 val numbers = listOf("one", "two", "three", "four")
 println(numbers.associateWith { it.length })

执行结果会转化为Map:

{one=3, two=3, three=5, four=4}

1.2、Set

Set内部是用Map实现的,Set相关的实现详见:Java Collection系列之:HashSet、LinkedHashSet、TreeSet的使用及源码解析

        //Set常用API Set的默认实现 - LinkedHashSet(保留元素插入的顺序)
        val numSet = setOf("one", "two", "three")
        println(numSet.first()) // one
        println(numSet.last()) // three
        for (index in numSet.indices) {
            //Set遍历 index位置
            println("index:$index")  //index:0  index:1   index:2
        }
        numSet.forEach {
            //Set遍历 Entry
            println(it) // one  two  three
        }
        numSet.forEachIndexed { index, entry ->
            //Set遍历  index & Entry
            println("index:$index, entry:$entry")
            /**
             * 执行结果:
             * index: 0, entry: one
             * index: 1, entry: two
             * index: 2, entry: three
             */
        }
        //Set之间的比较
        val numSet2 = setOf("two", "one", "three")
        println("numSet==numSet2:${numSet == numSet2}") //true  内容一致为true

        //可变Set
        val variableSet = mutableSetOf("one", "two", "three")
        variableSet.add("four")
        println(variableSet) // [one, two, three, four]
        variableSet.remove("two")
        println(variableSet) // [one, three, four]

        //union()并集、intersect()交集
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值