Kotlin集合操作整理

一、转换类

1.1转换为数组

集合类提供了toIntArray()、toDoubleArray()、toFloatArray()、toBetArray()等函数,将集合转换成相应的数组。

例:toIntArray()方法

public fun Collection<Int>.toIntArray(): IntArray {
    val result = IntArray(size)
    var index = 0
    for (element in this)
        result[index++] = element
    return result
}

 

 

例子:

fun listToArray(){
    val list = listOf<Int>(1,2,3,4,5,6)         // 声明一个Int类型的List
    val listArray = list.toIntArray()           // 转换

    println(list.javaClass.toString())          // 打印list的类型
    println(listArray.javaClass.toString())     // 打印listArray的类型
    println(listArray[1])
}
class java.util.Arrays$ArrayList
class [I
2

 

1.2转换为集合 

集合类提供了toList()、toMutableList()、toSet()、toMutableSet()、toHashSet()、toMap()等高阶函数将一个集合或者数组转换成相应等集合类型。

例:toList()方法

public fun <T> Iterable<T>.toList(): List<T> {
    if (this is Collection) {
        return when (size) {
            0 -> emptyList()
            1 -> listOf(if (this is List) get(0) else iterator().next())
            else -> this.toMutableList()
        }
    }
    return this.toMutableList().optimizeReadOnlyList()
}

例子:

// 数组转集合
fun arrayToList() {
    val arr = arrayOf(1,3,5,7,9)
    val list = arr.toList()
    println("变量arr的类型为:${arr.javaClass}")
    println("变量list的类型为:${list.javaClass}")
    println(list[1])
}

// 集合转集合,这里用Set转List

fun listToList(){
    val set = setOf(1)
    val setTolist = set.toList()
    
    println("变量set的类型为:${set.javaClass}")
    println("变量setTolist的类型为:${setTolist.javaClass}")
    println(setTolist[0])
}
变量arr的类型为:class [Ljava.lang.Integer;
变量list的类型为:class java.util.ArrayList
3
变量set的类型为:class java.util.Collections$SingletonSet
变量setTolist的类型为:class java.util.Collections$SingletonList
1

 

二、操作类 

2.1元素操作符

  • contains(元素) : 检查集合中是否包含指定的元素,若存在则返回true,反之返回false
fun testContains() {
    val list = listOf<Int>(1, 2, 3, 4)
    println(list.contains(1))
}
true
  • elementAt(index) : 获取对应下标的元素。若下标越界,会抛出IndexOutOfBoundsException(下标越界)异常,同get(index)一样
fun testElementAt(){
    val list = listOf<Int>(1, 2, 3, 4)
    println(list.elementAt(2))
}
3
  • elementAtOrElse(index,{...}) : 获取对应下标的元素。若下标越界,返回默认值,此默认值就是你传入的下标的运算值

/**
 * Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this list.
 * 
 * @sample samples.collections.Collections.Elements.elementAtOrElse
 */
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T {
    return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index)
}

 

  • elementAtOrNull(index) : 获取对应下标的元素。若下标越界,返回null
  • first() : 获取第一个元素,若集合为空集合,这会抛出NoSuchElementException异常

fun testListFirst() {
    val list = listOf<Int>(1, 2, 3, 4)
    val first = list.first()
    println(first)
}

1
  • first{} : 获取指定元素的第一个元素。若不满足条件,则抛出NoSuchElementException异常
/**
 * Returns the first element matching the given [predicate].
 * @throws [NoSuchElementException] if no such element is found.
 */
public inline fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T {
    for (element in this) if (predicate(element)) return element
    throw NoSuchElementException("Collection contains no element matching the predicate.")
}
fun testListFirst2() {
    val list = listOf<Int>(1, 2, 3, 4)

    val first = list.first { isTwo(it) }
    println(first)
}

fun isTwo(value: Int):Boolean {
    return value == 2
}

1
  • firstOrNull() : 获取第一个元素,若集合为空集合,返回null
  • firstOrNull{} : 获取指定元素的第一个元素。若不满足条件,返回null
  • getOrElse(index,{...}) : 同elementAtOrElse一样

 

/**
 * Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this list.
 */
@kotlin.internal.InlineOnly
public inline fun <T> List<T>.getOrElse(index: Int, defaultValue: (Int) -> T): T {
    return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index)
}

 

fun testGetOrElse() {
    val listOf = listOf<Int>(1, 2, 3, 4)
    val orElse = listOf.getOrElse(8, ::initDefaultValue)
    println(orElse)
}

fun initDefaultValue(value: Int): Int {
    return 888
}

888

 

  • getOrNull(index) : 同elementAtOrNull一样
fun testgetOrNull() {
    val listOf = listOf<Int>(1, 2, 3, 4)
    val index2Value = listOf.getOrNull(2)
    println(index2Value)

    val index9Value = listOf.getOrNull(9)
    println(index9Value)
}

3
null
  • last() : 同first()相反
  • last{} : 同first{}相反
fun testlistLast() {
    val list = listOf<Int>(1, 2, 3, 4)
    val last = list.last()
    println(last)

    val last1 = list.last {
        it < 2
    }

    println(last1)
}

4
1
  • lastOrNull{} : 同firstOrNull()相反
  • lastOrNull() : 同firstOrNull{}相反
  • indexOf(元素) : 返回指定元素的下标,若不存在,则返回-1
fun testIndexOf() {
    val listOf = listOf<Int>(1, 2, 3, 4)
    val indexOf_value_1 = listOf.indexOf(1)
    val indexOf_value_0 = listOf.indexOf(0)
    println("$indexOf_value_0;$indexOf_value_1")
}

-1;0
  • indexOfFirst{...} : 返回第一个满足条件元素的下标,若不存在,则返回-1
fun testIndexOfFirst() {
    val listOf = listOf<Int>(1, 2, 3, 4)
    val indexOfFirst = listOf.indexOfFirst {
        it > 3
    }

    println(indexOfFirst)

    val indexOfFirst1 = listOf.indexOfFirst {
        it > 10
    }

    println(indexOfFirst1)
}

3
-1
  • indexOfLast{...} : 返回最后一个满足条件元素的下标,若不存在,则返回-1
fun testIndexOfLast() {
    val list = listOf<Int>(1, 2, 3, 4)
    val indexOfLast = list.indexOfLast {
        it > 2
    }
    println(indexOfLast)

    val indexOfLast1 = list.indexOfLast { it > 9 }
    println(indexOfLast1)
}

3
-1
  • single() : 若集合的长度等于0,则抛出NoSuchElementException异常,若等于1,则返回第一个元素。反之,则抛出IllegalArgumentException异常
fun testSingle() {
    val listOf = listOf<Int>(4)
    val single = listOf.single()
    println(single)
}

4
  • single{} : 找到集合中满足条件的元素,若元素满足条件,则返回该元素。否则会根据不同的条件,抛出异常。这个方法慎用
fun testSingleTwo() {
    val listOf = listOf<Int>(5)
    val single = listOf.single { it > 2 }
    println(single)
}

5
  • singleOrNull() : 若集合的长度等于1,则返回第一个元素。否则,返回null
  • singleOrNull{} : 找到集合中满足条件的元素,若元素满足条件,则返回该元素。否则返回null
  • forEach{...} : 遍历元素。一般用作元素的打印
  • forEachIndexed{index,value} : 遍历元素,可获得集合中元素的下标。一般用作元素以及下标的打印
fun testforEachIndexedTwo() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6)
    listOf.forEachIndexed {index, value ->
        println("index:$index;value:$value")
    }
}

index:0;value:1
index:1;value:2
index:2;value:3
index:3;value:4
index:4;value:5
index:5;value:6
  • componentX() : 这个函数在前面的章节中提过多次了。用于获取元素。其中的X只能代表1..5。
fun testComponentX() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6)
    val component1 = listOf.component1()
    val component2 = listOf.component2()
    println("component1=$component1;component2=$component2")
}

component1=1;component2=2

2.2顺序操作符

  • reversed() : 反序。即和初始化的顺序反过来。
fun testReversed() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6)
    println(listOf.reversed())
}

[6, 5, 4, 3, 2, 1]
  • sorted() : 自然升序。 

fun testSorted() {
    val listOf = listOf<Int>(3, 2, 3, 5, 4, 1)
    println(listOf.sorted())
}
[1, 2, 3, 3, 4, 5]

 

  • sortedBy{} : 根据条件升序,即把不满足条件的放在前面,满足条件的放在后面
fun testSortedBy() {
    val listOf = listOf<Int>(3, 2, 3, 5, 4, 1)
    val sortedBy = listOf.sortedBy {
        it > 2
    }
    println(sortedBy)
}
[2, 1, 3, 3, 5, 4]

 

  • sortedDescending() : 自然降序。
fun testsortedDescending() {
    val listOf = listOf<Int>(3, 2, 3, 5, 4, 1)
    println(listOf.sortedDescending())
}
[5, 4, 3, 3, 2, 1]

 

  • sortedByDescending{} : 根据条件降序。
fun testsortedByDescending() {
    val listOf = listOf<Int>(3, 2, 3, 5, 4, 1)
    val sortedByDescending = listOf.sortedByDescending { it > 3 }
    println(sortedByDescending)
}
[5, 4, 3, 2, 3, 1]

 

 

2.3映射操作符

  • map{...} : 把每个元素按照特定的方法进行转换,组成一个新的集合。
fun testMap() {
    val listOf = listOf<Int>(3, 2, 3, 5, 4, 1)
    val map = listOf.map { it * 2 }
    println(map)
}
[6, 4, 6, 10, 8, 2]
  • mapNotNull{...} : 同map{}函数的作用相同,只是过滤掉转换之后为null的元素
fun mapNotNull() {
    val listOf = listOf<Int?>(3, 2, 3, 5, 4, null)
    val map = listOf.mapNotNull {
        it?.let {
            it * 3
        }
    }
    println(map)
}
[9, 6, 9, 15, 12]

 

  • mapIndexed{index,result} : 把每个元素按照特定的方法进行转换,只是其可以操作元素的下标(index),组成一个新的集合。
fun testMapIndexed() {
    val listOf = listOf<Int>(3, 2, 3, 5, 4, 1)
    listOf.mapIndexed { index, result ->
       println("$index,$result")
    }
}

0,3
1,2
2,3
3,5
4,4
5,1

 

fun testMapIndexed() {
    val listOf = listOf<Int>(3, 2, 3, 5, 4, 1)
    val mapIndexed = listOf.mapIndexed { index, result ->
        result * 9
    }
    println(mapIndexed)
}

[27, 18, 27, 45, 36, 9]

fun testMapIndexed() {
    val listOf = listOf<Int>(3, 2, 3, 5, 4, 1)
    val mapIndexed = listOf.mapIndexed { index, result ->
        if (index > 3) {
            result * 9
        } else result

    }
    println(mapIndexed)
}

[3, 2, 3, 5, 36, 9]

 

  • mapIndexedNotNull{index,result} : 同mapIndexed{}函数的作用相同,只是过滤掉转换之后为null的元素
fun mapIndexedNotNull() {
    val listOf = listOf<Int?>(3, 2, 3, 5, 4, null)
    val mapIndexed = listOf.mapIndexedNotNull() { index, result ->
        if (index > 3) {
            result?.let {
                result * 9
            }
        } else result

    }
    println(mapIndexed)
}

[3, 2, 3, 5, 36]

 

  • flatMap{...} : 根据条件合并两个集合,组成一个新的集合。flatMap  遍历所有的元素 ,为每一个创建一个集合 ,最后把所有的集合放在一个集合中。 

/**
 * Returns a single list of all elements yielded from results of [transform] function being invoked on each element of original collection.
 * 
 * @sample samples.collections.Collections.Transformations.flatMap
 */
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

 


/**
 * Appends all elements yielded from results of [transform] function being invoked on each element of original collection, to the given [destination].
 */
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(destination: C, transform: (T) -> Iterable<R>): C {
    for (element in this) {
        val list = transform(element)
        destination.addAll(list)
    }
    return destination
}

 

fun testflatMap() {
    val listOf1 = listOf<Int>(3, 2, 3, 5, 4, 1)
    val flatMap = listOf1.flatMap {
        listOf(it +1)
    }
    println(flatMap)
}
[4, 3, 4, 6, 5, 2]

 

  • groupBy{...} : 分组。即根据条件把集合拆分为为一个Map<K,List<T>>类型的集合。

fun testGroupBy() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val groupBy = listOf.groupBy {
        if (it > 4) "big" else "small"
    }
    println(groupBy)
}

{small=[1, 2, 3, 4], big=[5, 6, 7]}

 

2.4过滤操作符

  • filter{...} : 把不满足条件的元素过滤掉

fun testFilter() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val filter = listOf.filter {
        it > 3
    }
    println(filter)
}

[4, 5, 6, 7]
  • filterIndexed{...} : 和filter{}函数作用类似,只是可以操作集合中元素的下标(index)
fun testFilterIndexed() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val filterIndexed = listOf.filterIndexed { index, result ->
        index < 5 && result > 1
    }

    println(filterIndexed)
}

[2, 3, 4, 5]

 

  • filterNot{...} : 和filter{}函数的作用相反

fun testFilterNot() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val filterNot = listOf.filterNot {
        it > 4
    }

    println(filterNot)
}
[1, 2, 3, 4]

 

  • filterNotNull() : 过滤掉集合中为null的元素。
fun testFilterNotNull() {
    val listOf = listOf<Int?>(1, 2, 3, 4, 5, 6, null)
    val filterNotNull = listOf.filterNotNull()
    println(filterNotNull)
}
[1, 2, 3, 4, 5, 6]

 

  • take(num) : 返回集合中前num个元素组成的集合

 

fun testTake() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val take = listOf.take(2)
    println(take)
}
[1, 2]

 

  • takeWhile{...} : 循环遍历集合,从第一个元素开始遍历集合,当第一个出现不满足条件元素的时候,退出遍历。然后把满足条件所有元素组成的集合返回。

fun testTakeWhile() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val takeWhile = listOf.takeWhile {
        it < 6
    }
    println(takeWhile)
}
[1, 2, 3, 4, 5]
  • takeLast(num) : 返回集合中后num个元素组成的集合
fun testTakeLast() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val take = listOf.takeLast(2)
    println(take)
}
[6, 7]
  • takeLastWhile{...} : 循环遍历集合,从最后一个元素开始遍历集合,当第一个出现不满足条件元素的时候,退出遍历。然后把满足条件所有元素组成的集合返回。
fun testTakeLastWhile() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val takeLastWhile = listOf.takeLastWhile {
        it > 5
    }
    println(takeLastWhile)
}
[6, 7]
  • drop(num) : 过滤集合中前num个元素
fun testDrop() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val drop = listOf.drop(3)
    println(drop)
}
[4, 5, 6, 7]
  • dropWhile{...} : 相同条件下,和执行takeWhile{...}函数后得到的结果相反
fun testDropWhile() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val dropWhile = listOf.dropWhile {
        it < 6
    }
    println(dropWhile)
}
[6, 7]

 

  • dropLast(num) : 过滤集合中后num个元素
fun testDropLast() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val dropLast = listOf.dropLast(2)
    println(dropLast)
}
[1, 2, 3, 4, 5]

 

  • dropLastWhile{...} : 相同条件下,和执行takeLastWhile{...}函数后得到的结果相反
fun testDropLastWhile() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val dropLastWhile = listOf.dropLastWhile {
        it > 5
    }
    println(dropLastWhile)
}
[1, 2, 3, 4, 5]

 

  • distinct() : 去除重复元素

fun testDistinct() {
    val listOf = listOf<Int>(1, 1, 3, 4, 5, 5, 7)
    val distinct = listOf.distinct()
    println(distinct)
}
[1, 3, 4, 5, 7]

 

  • distinctBy{...} : 根据操作元素后的结果去除重复元素
/**
 * Returns a list containing only elements from the given collection
 * having distinct keys returned by the given [selector] function.
 * 
 * Among elements of the given collection with equal keys, only the first one will be present in the resulting list.
 * The elements in the resulting list are in the same order as they were in the source collection.
 * 
 * @sample samples.collections.Collections.Transformations.distinctAndDistinctBy
 */
public inline fun <T, K> Iterable<T>.distinctBy(selector: (T) -> K): List<T> {
    val set = HashSet<K>()
    val list = ArrayList<T>()
    for (e in this) {
        val key = selector(e)
        if (set.add(key))
            list.add(e)
    }
    return list
}

 

fun testDistinctBy() {
    val listOf = listOf<Int>(1, 1, 3, 4, 5, 5, 7)
    println(listOf.distinctBy { it + 2 })
}
[1, 3, 4, 5, 7]
其实这个方法是去除了it+2的重复的值,最终保存回到集合中的还是it 本身

 

  • slice : 过滤掉所有不满足执行下标的元素。
fun testSlice() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val slice = listOf.slice(2..3)
    println(slice)
}

[3, 4]


fun testSlice2() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    println(listOf.slice(listOf(1, 3)))
}

[2, 4]

 

/**
 * Returns a list containing elements at indices in the specified [indices] range.
 */
public fun <T> List<T>.slice(indices: IntRange): List<T> {
    if (indices.isEmpty()) return listOf()
    return this.subList(indices.start, indices.endInclusive + 1).toList()
}

/**
 * Returns a list containing elements at specified [indices].
 */
public fun <T> List<T>.slice(indices: Iterable<Int>): List<T> {
    val size = indices.collectionSizeOrDefault(10)
    if (size == 0) return emptyList()
    val list = ArrayList<T>(size)
    for (index in indices) {
        list.add(get(index))
    }
    return list
}

 

 

2.5生产操作符

  • plus() : 合并两个集合中的元素,组成一个新的集合。也可以使用符号+
fun testPlus() {
    val listOf1 = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val listOf2 = listOf<Int>(1, 2, 3, 4, 5, 6, 7)

    val plus = listOf1.plus(listOf2)
    println(plus)
}

[1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7]
  • zip : 由两个集合按照相同的下标组成一个新集合。该新集合的类型是:List<Pair>
fun testZip() {
    val listOf1 = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val listOf2 = listOf<Int>(8, 9, 10, 11, 12, 13, 14)
    val zip = listOf1.zip(listOf2)
    println(zip)

    zip.forEach {
        println("""${it.first};${it.second}""")
    }
}

[(1, 8), (2, 9), (3, 10), (4, 11), (5, 12), (6, 13), (7, 14)]
1;8
2;9
3;10
4;11
5;12
6;13
7;14
  • unzip : 和zip的作用相反。把一个类型为List<Pair>的集合拆分为两个集合。看下面的例子
fun testUnZip() {
    val listOf1 = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val listOf2 = listOf<Int>(8, 9, 10, 11, 12, 13, 14)
    val zip = listOf1.zip(listOf2)
    val unzip = zip.unzip()
    println(unzip.first)
    println(unzip.second)
}

[1, 2, 3, 4, 5, 6, 7]
[8, 9, 10, 11, 12, 13, 14]
  • partition : 判断元素是否满足条件把集合拆分为有两个Pair组成的新集合。
fun testPartition() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val partition = listOf.partition {
        it > 3
    }
    println(partition.first)
    println(partition.second)
}

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

2.6统计操作符

  • any() : 判断是不是一个集合,若是,则在判断集合是否为空,若为空则返回false,反之返回true,若不是集合,则返回hasNext
fun testAny() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    println(listOf.any())
    val emptyList = emptyList<Int>()
    println(emptyList.any())
}

true
false
  • any{...} : 判断集合中是否存在满足条件的元素。若存在则返回true,反之返回false
fun testAny2() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val any1 = listOf.any {
        it == 3
    }
    println(any1)

    val any2 = listOf.any {
        it == 9
    }
    println(any2)
}

true
false

 

  • all{...} : 判断集合中的所有元素是否都满足条件。若是则返回true,反之则返回false
fun testAll() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val all = listOf.all {
        it > 0
    }
    println(all)

    val listOf2 = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val all1 = listOf2.all {
        it > 5
    }
    println(all1)
}
true
false

 

  • none() : 和any()函数的作用相反
fun testNOne() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val none = listOf.none()
    println(none)
}

false

 

  • none{...} : 和all{...}函数的作用相反
fun testNone2() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val none = listOf.none {
        it > 0
    }
    println(none)

    val none1 = listOf.none {
        it > 3
    }
    println(none1)
}
false
false

 

  • max() : 获取集合中最大的元素,若为空元素集合,则返回null
fun testMax() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val max = listOf.max()
    println(max)
}
7

 

  • maxBy{...} : 获取方法处理后返回结果最大值对应那个元素的初始值,如果没有则返回null
fun testMaxBy() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val maxBy = listOf.maxBy {
        it > 5
    }
    println(maxBy)
}

6

 

@Deprecated("Use maxByOrNull instead.", ReplaceWith("maxByOrNull(selector)"))
@DeprecatedSinceKotlin(warningSince = "1.4")
public inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R): T? {
    return maxByOrNull(selector)
}

/**
 * Returns the first element yielding the largest value of the given function or `null` if there are no elements.
 * 
 * @sample samples.collections.Collections.Aggregates.maxByOrNull
 */
@SinceKotlin("1.4")
public inline fun <T, R : Comparable<R>> Iterable<T>.maxByOrNull(selector: (T) -> R): T? {
    val iterator = iterator()
    if (!iterator.hasNext()) return null
    var maxElem = iterator.next()
    if (!iterator.hasNext()) return maxElem
    var maxValue = selector(maxElem)
    do {
        val e = iterator.next()
        val v = selector(e)
        if (maxValue < v) {
            maxElem = e
            maxValue = v
        }
    } while (iterator.hasNext())
    return maxElem
}
  • min() : 获取集合中最小的元素,若为空元素集合,则返回null
fun testMin() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val min = listOf.min()
    println(min)
}
1

 

  • minBy{...} : 获取方法处理后返回结果最小值对应那个元素的初始值,如果没有则返回null
fun testMinBy() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val minBy = listOf.minBy {
        it + 2
    }
    println(minBy)
}
1

 

  • sum() : 计算出集合元素累加的结果。
fun testSum() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val sum = listOf.sum()
    println(sum)
}
28
  • sumBy{...} : 根据元素运算操作后的结果,然后根据这个结果计算出累加的值。
fun testSumBy() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val sumBy = listOf.sumBy {
        it + 2
    }
    println(sumBy)
}

42
  • sumByDouble{...} : 和sumBy{}相似,不过sumBy{}是操作Int类型数据,而sumByDouble{}操作的是Double类型数据
fun testsumByDouble() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val sumByDouble = listOf.sumByDouble {
        it.toDouble()
    }
    println(sumByDouble)
}
28.0

 

  • average() : 获取平均数

/**
 *   获取平均数
 */
fun testAverage() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val average = listOf.average()
    println(average)
}
4.0
  • reduce{...} : 从集合中的第一项到最后一项的累计操作。
fun testReduce() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val reduce = listOf.reduce { result, next ->
        result + next
    }
    println(reduce)
}
28
  • reduceIndexed{...} : 和reduce{}作用相同,只是其可以操作元素的下标(index)
fun testReduceIndexed() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val reduceRightIndexed = listOf.reduceRightIndexed { index, result, next ->
        index + result + next
    }
    println(reduceRightIndexed)
}
43

 

  • reduceRight{...} : 从集合中的最后一项到第一项的累计操作。
fun testReduceRight() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val reduceRight = listOf.reduceRight { result, next ->
        result + next
    }
    println(reduceRight)
}

28
  • reduceRightIndexed{...} : 和reduceRight{}作用相同,只是其可以操作元素的下标(index)
fun reduceRightIndexed() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val reduceRightIndexed = listOf.reduceRightIndexed { index, result, next ->
        index + result + next
    }
    println(reduceRightIndexed)
}
43
  • fold{...} : 和reduce{}类似,但是fold{}有一个初始值
fun testFoldValue() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val fold = listOf.fold(100) { result, next ->
        result + next
    }
    println(fold)
}
128

 

  • foldIndexed{...} : 和reduceIndexed{}类似,但是foldIndexed{}有一个初始值
fun testFoldIndexed() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val foldIndexed = listOf.foldIndexed(100) { index, result, next ->
        println(index)
        index + result + next
    }
    println(foldIndexed)
}
149
  • foldRight{...} : 和reduceRight{}类似,但是foldRight{}有一个初始值
fun testFoldRight() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val foldRight = listOf.foldRight(100) { result, next ->
        result + next
    }
    println(foldRight)
}
128
  • foldRightIndexed{...} : 和reduceRightIndexed{}类似,但是foldRightIndexed{}有一个初始值
fun testFoldRightIndexed() {
    val listOf = listOf<Int>(1, 2, 3, 4, 5, 6, 7)
    val foldRightIndexed = listOf.foldRightIndexed(100) { index, result, next ->
        index + result + next
    }
    println(foldRightIndexed)
}
149

 

 

 

 

 

 

 

 

 

 

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值