kotlin中的List集合类

 

kotlin中的List集合类

版权声明:本文为博主原创文章,未经博主容许不得转载。 https://blog.csdn.net/mjb00000/article/details/79298165

Kotlin的集合分类:java

  • 可变集合类(Mutable)
  • 不可变集合类(Immutable)。

集合类存放的都是对象的引用,而非对象自己,咱们一般说的集合中的对象指的是集合中对象的引用。集合类型主要有List(列表),Set(集),Map(映射)。android

kotlin中List与Java同样都是实现了Collection接口,源码以下:

public interface List<out E> : Collection<E> {
    // Query Operations override val size: Int override fun isEmpty(): Boolean override fun contains(element: @UnsafeVariance E): Boolean override fun iterator(): Iterator<E> // Bulk Operations override fun containsAll(elements: Collection<@UnsafeVariance E>): Boolean // Positional Access Operations /** * Returns the element at the specified index in the list. */ public operator fun get(index: Int): E // Search Operations /** * Returns the index of the first occurrence of the specified element in the list, or -1 if the specified * element is not contained in the list. */ public fun indexOf(element: @UnsafeVariance E): Int /** * Returns the index of the last occurrence of the specified element in the list, or -1 if the specified * element is not contained in the list. */ public fun lastIndexOf(element: @UnsafeVariance E): Int // List Iterators /** * Returns a list iterator over the elements in this list (in proper sequence). */ public fun listIterator(): ListIterator<E> /** * Returns a list iterator over the elements in this list (in proper sequence), starting at the specified [index]. */ public fun listIterator(index: Int): ListIterator<E> // View /** * Returns a view of the portion of this list between the specified [fromIndex] (inclusive) and [toIndex] (exclusive). * The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. * * Structural changes in the base list make the behavior of the view undefined. */ public fun subList(fromIndex: Int, toIndex: Int): List<E> }

1.建立不可变List

使用listOf函数来构建一个不可变的List(只读的List),listOf这个构建函数有下面3个重载函数。
源码:bash

/** Returns a new read-only list of given elements. The returned list is serializable (JVM). */ public fun <T> listOf(vararg elements: T): List<T> = if (elements.size > 0) elements.asList() else emptyList() /** Returns an empty read-only list. The returned list is serializable (JVM). */ @kotlin.internal.InlineOnly public inline fun <T> listOf(): List<T> = emptyList() /** * Returns an immutable list containing only the specified object [element]. * The returned list is serializable. */ @JvmVersion public fun <T> listOf(element: T): List<T> = java.util.Collections.singletonList(element)

这些函数建立的List都是是只读的,不可变的、可序列化的。其中,markdown

  • listOf()用于建立没有元素的空List
  • listOf(vararg elements: T)用于建立拥有多个元素的List
  • listOf(element: T)用于建立只有一个元素的List
建立一个空List
val mList: List<Int> = listOf() println(mList)
  • 1
  • 2

打印输出:app

[]ide

建立只有一个元素的List
val mList: List<Int> = listOf(0) println(mList)
  • 1
  • 2

打印输出:函数

[0]post

建立多个元素的List
val mList: List<Int> = listOf(1, 3, 5, 7, 9) println(mList)
  • 1
  • 2

打印输出:gradle

[1, 3, 5, 7, 9]ui

2.建立可变集合

List的可变集合有两种,源码以下:

/** Returns an empty new [MutableList]. */ @SinceKotlin("1.1") @kotlin.internal.InlineOnly public inline fun <T> mutableListOf(): MutableList<T> = ArrayList() /** Returns an empty new [ArrayList]. */ @SinceKotlin("1.1") @kotlin.internal.InlineOnly public inline fun <T> arrayListOf(): ArrayList<T> = ArrayList() /** Returns a new [MutableList] with the given elements. */ public fun <T> mutableListOf(vararg elements: T): MutableList<T> = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true)) /** Returns a new [ArrayList] with the given elements. */ public fun <T> arrayListOf(vararg elements: T): ArrayList<T> = if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))

 

  • mutableListOf(): MutableList
  • arrayListOf(): ArrayList

在MutableList中,除了继承List中的那些函数外,另外新增了add/addAll、remove/removeAll/removeAt、set、clear、retainAll等更新修改的操做函数。

MutableList源码:
public interface MutableList<E> : List<E>, MutableCollection<E> {
    // Modification Operations override fun add(element: E): Boolean override fun remove(element: E): Boolean // Bulk Modification Operations override fun addAll(elements: Collection<E>): Boolean /** * Inserts all of the elements in the specified collection [elements] into this list at the specified [index]. * * @return `true` if the list was changed as the result of the operation. */ public fun addAll(index: Int, elements: Collection<E>): Boolean override fun removeAll(elements: Collection<E>): Boolean override fun retainAll(elements: Collection<E>): Boolean override fun clear(): Unit // Positional Access Operations /** * Replaces the element at the specified position in this list with the specified element. * * @return the element previously at the specified position. */ public operator fun set(index: Int, element: E): E /** * Inserts an element into the list at the specified [index]. */ public fun add(index: Int, element: E): Unit /** * Removes an element at the specified [index] from the list. * * @return the element that has been removed. */ public fun removeAt(index: Int): E // List Iterators override fun listIterator(): MutableListIterator<E> override fun listIterator(index: Int): MutableListIterator<E> // View override fun subList(fromIndex: Int, toIndex: Int): MutableList<E> }

 

可变集合示例

val mList = mutableListOf(2, 4, 6, 8, 10) println(mList) mList.add(0, 0) // 在下标为0的地方添加一个0元素 println(mList)

打印输出:

[2, 4, 6, 8, 10]
[0, 2, 4, 6, 8, 10]

toMutableList()转换函数:

若是已经有了一个不可变的List,想把他转换成可变的List,可直接调用转换函数toMutableList()

// 不可变集合 val mList: List<Int> = listOf(1, 3, 5, 7, 9) // 调用toMutableList()函数进行转换 val mMutableList = mList.toMutableList() // 调用可变函数的add()方法 mMutableList.add(11) // 打印输出 println(mMutableList)

打印输出:

[1, 3, 5, 7, 9, 11]

3.遍历List元素

使用Iterator迭代器遍历List元素
val mList: List<Int> = listOf(0, 1, 2, 3, 4, 5) val mIndex = mList.iterator() while (mIndex.hasNext()) { println(mIndex.next()) }

打印输出:

0
1
2
3
4
5

使用for循环遍历List元素
val mList: List<Int> = listOf(0, 1, 2, 3, 4, 5) for (i in mList.indices){ println(mList[i]) }

打印输出:

0
1
2
3
4
5

逆向循环

for (i in mList.size downTo 0){ println("$i") }

打印输出:

6
5
4
3
2
1
0

使用函数withIndex()遍历List元素
val mList: List<Int> = listOf(0, 1, 2, 3, 4, 5) for ((index, value) in mList.withIndex()) { println("下标 = $index\t值 = $value") }

打印输出:

下标 = 0 值 = 0
下标 = 1 值 = 1
下标 = 2 值 = 2
下标 = 3 值 = 3
下标 = 4 值 = 4
下标 = 5 值 = 5

使用forEach遍历List元素
val mList: List<Int> = listOf(0, 1, 2, 3, 4, 5) mList.forEach { println(it) }

打印输出:

0
1
2
3
4
5

4.常见的List元素操做函数

add, remove, set, clear

这几个操做符与Java中的List同样。

retainAll

取两个集合交集:

val mList1 = mutableListOf(0, 1, 3, 5, 7, 9) val mList2 = mutableListOf(0, 2, 4, 6, 8, 10) mList1.retainAll(mList2) println(mList1)

打印输出:

[0]

contains(element: T): Boolean

判断集合中是否有指定元素,有就返回true,不然返回false 。

val mList = mutableListOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // 取集合中存在的元素 println(mList.contains(5)) // 取集合中不存在的元素 println(mList.contains(20))

打印输出:

true
false

elementAt(index: Int): T

查找下标对应的元素,若是下标越界会抛IndexOutOfBoundsException。

val mList = mutableListOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) println("下标为5的元素值:${mList.elementAt(5)}")

打印输出:

下标为5的元素值:5

elementAtOrElse(index: Int, defaultValue: (Int) -> T): T

查找下标对应元素,若是越界会根据方法返回默认值。

val mList = mutableListOf(0,1,2,3,4,5) println(mList.elementAtOrElse(5, {0})) println(mList.elementAtOrElse(6, {0}))

打印输出:

5
0

elementAtOrNull(index: Int): T?

查找下标对应元素,若是越界就返回null

val mList = mutableListOf(0,1,2,3,4,5) println(mList.elementAtOrNull(6))

打印输出:

null

first()

返回集合第1个元素,若是是空集,抛出异常java.util.NoSuchElementException: List is empty.

val mList = mutableListOf(0,1,2,3,4,5) println(mList.first())

打印输出:

0

firstOrNull(): T?

返回集合第1个元素,若是是空集, 对空指针异常处理的函数,若是集合为空,则返回null。

val mList = listOf<Int>() println(mList.firstOrNull())

打印输出:

null

first(predicate: (T) -> Boolean): T

返回符合条件的第一个元素,没有则抛异常NoSuchElementException 。

val mList = listOf(1, 2, 3) println(mList.first { it % 2 == 0 })

打印输出:

2

对应的有针对异常处理的函数firstOrNull(predicate: (T) -> Boolean): T? ,返回符合条件的第一个元素,没有就返回null

indexOf(element: T): Int

返回指定元素的下标,没有就返回-1

val mList = listOf(1, 2, 3) println(mList.indexOf(3)) println(mList.indexOf(0))

打印输出:

2
-1

indexOfFirst(predicate: (T) -> Boolean): Int

返回第一个符合条件的元素的下标,没有就返回-1 。

val mList = listOf(1, 2, 3) println(mList.indexOfFirst { it == 2})

集合中元素2对应的下标是1,因此打印输出:

1

indexOfLast(predicate: (T) -> Boolean): Int

返回最后一个符合条件的元素下标,没有就返回-1 。

val mList = listOf("java for android", "gradle for android", "kotlin for android") println(mList.indexOfLast { it.contains("android")})

打印输出:

2

集合元素kotlin for android的下标恰好对应的是2 。

last()

返回集合最后一个元素,空集则抛出异常NoSuchElementException。

val mList = listOf("java for android", "gradle for android", "kotlin for android") println(mList.last())

打印输出:

kotlin for android

last(predicate: (T) -> Boolean): T

返回符合条件的最后一个元素,没有就抛NoSuchElementException

val mList = listOf("java for android", "gradle for android", "kotlin for android") println(mList.last { it.contains("android") })

打印输出:

kotlin for android

lastOrNull(predicate: (T) -> Boolean): T?

返回符合条件的最后一个元素,没有就返回null

val mList = listOf("java for android", "gradle for android", "kotlin for android") println(mList.lastOrNull { it.contains("android") }) println(mList.lastOrNull { it.contains("JavaScript") })

打印输出:

kotlin for android
null

lastIndexOf(element: T): Int

返回符合条件的最后一个元素的下标,没有就返回-1

val mList = listOf("java for android", "android", "kotlin", "android") println(mList.lastIndexOf("android")) println(mList.lastIndexOf("JavaScript"))

打印输出:

3
-1

single(): T

该集合若是只有1个元素,则返回该元素。为空时会抛出NoSuchElementException 异常,存在多个元素时会抛 IllegalArgumentException异常。

val mList = listOf(1) println(mList.single())

打印输出:

1

singleOrNull(): T?

返回符合条件单个元素, 若是集合为空或者有多个元素,则返回null

val mList = listOf(1, 2) println(mList.singleOrNull())

打印输出:

null

single(predicate: (T) -> Boolean): T

返回符合条件的单个元素,若有没有符合的抛异常NoSuchElementException,或超过一个的抛异常IllegalArgumentException。

val mList = listOf(1) println(mList.single { it == 1 }) println(mList.single { it == 2 })

打印输出:

1
Exception in thread “main” java.util.NoSuchElementException: Collection contains no element matching the predicate.
at KotlinUtilsTestKt.main(KotlinUtilsTest.kt:48)

singleOrNull(predicate: (T) -> Boolean): T?

返回符合条件单个元素,若是未找到符合的元素或找到多个元素,则返回null。

val mList = listOf(1, 2) println(mList.singleOrNull { it == 2 })

打印输出:

2

5.List集合运算的基本函数

any(): Boolean

判断集合元素,若是集合为空,返回false, 集合中存有一个或多个元素时返回true

val mList1 = arrayListOf(1, 2, 3, 4, 5) val mList2: ArrayList<Int> = arrayListOf() println(mList1.any()) println(mList2.any())

打印输出:

true
false

any(predicate: (T) -> Boolean): Boolean

判断集合元素,若是集合为空或者没有符号条件的元素返回false, 集合中存有一个或多个元素符合条件时返回true

val mList = arrayListOf(1, 2, 2, 3, 4, 5) println(mList.any { it == 2})

打印输出:

true

all(predicate: (T) -> Boolean): Boolean

当且仅当该集合中全部元素都知足条件时,返回true;不然都返回false。

val mList = arrayListOf(0, 2, 4, 6, 8) println(mList.all { it % 2 == 0 })

打印输出:

true

val mList = arrayListOf(0, 1, 2, 3, 4) println(mList.all { it % 2 == 0 })

打印输出:

false

none(): Boolean

若是集合中没有元素,则返回true,不然返回false。

val mList = arrayListOf(0, 1, 2, 3, 4) println(mList.none())

打印输出:

false

none(predicate: (T) -> Boolean): Boolean

若是集合中没有符合匹配条件的元素,返回true,不然返回false 。

val mList = arrayListOf(0, 1, 2, 3, 4) println(mList.none { it == 5 })

打印输出:

true

count(): Int

返回集合元素个数

val mList = arrayListOf(0, 1, 2, 3, 4) println(mList.count())

打印输:

5

count(predicate: (T) -> Boolean): Int

返回符合匹配条件的元素的个数

val mList = arrayListOf(0, 1, 2, 3, 4) println(mList.count { it % 2 == 0 })

打印输出:

3

max, min 查询最大,最小元素,空集返回null

max函数定义

public fun <T : Comparable<T>> Iterable<T>.max(): T? { val iterator = iterator() if (!iterator.hasNext()) return null var max = iterator.next() while (iterator.hasNext()) { val e = iterator.next() if (max < e) max = e } return max }

经过max函数源代码定义看出,max函数是经过迭代器遍历集合进行比较,返回最大元素。

min函数定义

public fun <T : Comparable<T>> Iterable<T>.min(): T? { val iterator = iterator() if (!iterator.hasNext()) return null var min = iterator.next() while (iterator.hasNext()) { val e = iterator.next() if (min > e) min = e } return min }

经过min函数源代码定义看出,min函数也是经过迭代器遍历集合进行比较,返回最小元素。

val mList = arrayListOf(0, 1, 2, 3) println(mList.max()) println(mList.min())

打印输出:

3
0

6.过滤操做函数

take(n: Int): List

take函数是根据传入的参数挑出该集合前n个元素的子集合

val mList = arrayListOf(0, 1, 2, 3) val mNewList = mList.take(2) println(mNewList)

打印mNewList集合元素:

[0, 1]

7.映射操做符

map(transform: (T) -> R): List

将集合中的元素经过转换函数transform映射后的结果,存到一个集合中返回。

val mList = mutableListOf(1, 3, 2, 4) println(mList.map { it + 1 })

打印输出:

[2, 4, 3, 5]

mapNotNull(transform: (T) -> R?)

遍历集合每一个元素,获得经过函数算子transform映射以后的值,剔除掉这些值中的null,返回一个无null元素的集合。

val mList = mutableListOf(1, null, 3, null, 2, 4) println(mList.mapNotNull { it })

打印输出:

[1, 3, 2, 4]

8.排序操做符

reversed(): List

倒序排列集合元素。如:[1, 2, 7, 6, 4, 5]排列后为:[5, 4, 6, 7, 2, 1]。

val mList = listOf(1, 3, 2, 4) println(mList.reversed())

打印输出:

[4, 2, 3, 1]

sorted(): List和sortedDescending(): List

升序排序和降序排序。

val mList = listOf(1, 3, 2, 4) println(mList.sorted()) println(mList.sortedDescending())

打印输出:

[1, 2, 3, 4]
[4, 3, 2, 1]

sortedBy和sortedByDescending

可变集合MutableList的排序操做。根据函数映射的结果进行升序排序和降序排序。

val mList = mutableListOf(1, 3, 2, 4) println(mList.sorted()) println(mList.sortedDescending())

打印输出:

[1, 2, 3, 4]
[4, 3, 2, 1]

9.生产操做符

zip(other: Iterable): List
val mList3 = arrayListOf("x1", "x2", "x3", "x4") val mList4 = arrayListOf("y1", "y2", "y3") println(mList3.zip(mList4))

打印输出:

[(x1, y1), (x2, y2), (x3, y3)]

plus(elements: Iterable): List

合并两个List

val mList1 = arrayListOf(0, 1, 2, 3) val mList2 = arrayListOf(4, 5, 6, 7, 8) println(mList1.plus(mList2))

打印输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8]

相关文章
相关标签/搜索