kotlin集合使用方法整理

Kotlin的集合分类:

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

集合类存放的都是对象的引用,而非对象本身,我们通常说的集合中的对象指的是集合中对象的引用。集合类型主要有List(列表),Set(集),Map(映射)。

1.创建不可变List

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

/** 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都是是只读的,不可变的、可序列化的。其中,

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

打印输出:

[]

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

打印输出:

[0]

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

打印输出:

[1, 3, 5, 7, 9]

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元素操作函数

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

4.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

5.过滤操作函数

take(n: Int): List

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

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

打印mNewList集合元素:

[0, 1]

6.映射操作符

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]

7.排序操作符

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]

8.生产操作符

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]



猜你喜欢

转载自blog.csdn.net/sunlit_6/article/details/80860810