Kotlin集合内置函数

1.LINQ-风格

    val words = "A long time ago in a galaxy far far away".split(" ")
    val shortWords = mutableListOf()
    words.getShortWordsTo(shortWords, 3)
    println(shortWords)//[ago, in, far, far]

getShortWordsTo

fun List.getShortWordsTo(shortWords: MutableList, maxLength: Int) {
    this.filterTo(shortWords) { it.length <= maxLength }
    val articles = setOf("a", "A", "an", "An", "the", "The")
    shortWords -= articles //removeAll
}

上面逻辑看起来似乎不太直观
LINQ:

    "A long time ago in a galaxy far far away"
        .split(" ")
        .filter { it.length <= 3 }
        .toMutableList()
        .let {
            val articles = setOf("a", "A", "an", "An", "the", "The")
            it.removeAll(articles)
            it
        }
        .run { println(this) }

apply代替let let返回block() 而apply返回this

    "A long time ago in a galaxy far far away"
        .split(" ")
        .filter { it.length <= 3 }
        .toMutableList()
        .apply {
            removeAll(setOf("a", "A", "an", "An", "the", "The"))
        }
        .joinToString(separator = "-", prefix = "{", postfix = "}")
        .run { println(this) }

2.kotlin标准库中内置的Iterable的扩展函数
准备容器数据

data class Product(val name: String, val price: Double, val isChecked: Boolean)
fun main() {
    var list = ArrayList()
    repeat(5) {
        list.add(Product("gaom$it", it.toDouble(), it >= 2))
    }
}

forEachIndexed

//带游标遍历 解构
    list.forEachIndexed { index, (name, _, isChecked) -> println("$index={$name, $isChecked}") }

any/all/count

    println(list.any { !it.isChecked })//任何item没有选中 , 则全选按钮置为 -未选中状态
    println(list.all { it.isChecked })//所有item选中 , 则全选按钮置为 -选中状态
    println(list.count { it.isChecked })// 选中状态商品数量

计算所选商品价格

    println(
        list
            .filter { it.isChecked }
            .map { it.price }//转换类型
//            .reduce{} //reduce与fold类似,但是没有初始值
            .fold(.0) { total, next -> total + next }
        //fold 折叠 计算init为初始值 可传入任意类型
    )

计算所选商品价格

    println(list
        .filter { it.isChecked }
        .sumByDouble { it.price })

partition 按条件分割trueList,falseList

    list.partition { it.isChecked }
        .run {
            //first list
            println(first.map { it.price }
                .fold(.0) { total, next -> total + next })
            //second list
            println(second.map { it.price }
                .fold(.0) { total, next -> total + next }
            )
        }

操作符 & 中缀

//操作符 -=
    val aList = mutableListOf(1, 2, 3)
    val bList = mutableListOf(1, 2, 3, 4)
    bList -= aList
    aList + listOf(1, 2)

//中缀 zip
    listOf(1, 2).zip(listOf(7, 8))//(1, 7) (2, 8)
    listOf(1, 2) zip listOf(7, 8)

list转换成map associate函数

    val numbers = listOf("one", "two", "three", "four")
    println(numbers.associateWith { value -> value.length })//key默认是集合中的元素 , 要求返回一个value
    //{one=3, two=3, three=5, four=4}

    println(numbers.associateBy { key -> key.first().toUpperCase() })//value默认是集合中的元素 , 要求返回一个key
    //{O=one, T=three, F=four}
    println(
        numbers.associateBy(
            keySelector = { it.first().toUpperCase() },
            valueTransform = { it.length })
    )
    //{O=3, T=5, F=4}

    val names = listOf("Alice Adams", "Brian Brown", "Clara Campbell")
    println(names.associate { name -> name.split(" ").let { it[0] to it[1] } })
    //{Alice=Adams, Brian=Brown, Clara=Campbell}

去重

    val distinctList = mutableListOf(0, 1, 2, 2, 3, 4, 4)
    println(distinctList.distinct()) // [0, 1, 2, 3, 4]
    //根据指定元素 而不是条件!!! it%2==0
    println(distinctList.distinctBy { it })

distinctBy源码

    public inline fun  Iterable.distinctBy(selector: (T) -> K): List {
    val set = HashSet()
    val list = ArrayList()
    for (e in this) {
        val key = selector(e)
        if (set.add(key))//HashSet作用就是去重复数据
            list.add(e)
    }
    return list
}

产生的最大值的原始元素

    val listMaxBy = listOf(1, 2, 2, 4)
    println("maxBy=${listMaxBy.maxBy { -it }}")//maxBy=1

none

val listMaxBy = listOf(1, 2, 2, 4)
println("none=${listMaxBy.none {  it==5 }}")//true

orEmpty

val listMaxBy = listOf(1, 2, 2, 4)
println("orEmpty=${listMaxBy.orEmpty()}")//orEmpty=[1, 2, 2, 4]

orEmpty源码

public inline fun  List?.orEmpty(): List = this ?: emptyList()

slice 相当于 Java subList

    val listMaxBy = listOf(1, 2, 2, 4)
    println("slice1=${listMaxBy.slice(1..3)}")//slice1=[2, 2, 4]
    println("slice2=${listMaxBy.slice(listOf(1,2))}")//slice2=[2, 2]

take 舍弃目标index之后的数据

val listMaxBy = listOf(1, 2, 2, 4)
println("take=${listMaxBy.take(3)}")//take=[1, 2, 2]

flatten 平铺

    val numberSets1 = listOf(setOf(1, 2, 3), setOf(4, 5, 6), setOf(7, 8))
    println("flatten=${numberSets1.flatten()}")//[1, 2, 3, 4, 5, 6, 7, 8]

rangeTo

    val numbersToList = (1..100).toList()

joinToString

    val numbersToList = (1..100).toList()
    println("numbersToList=${numbersToList.joinToString(limit = 10, truncated = "<...>")}")
    //1, 2, 3, 4, 5, 6, 7, 8, 9, 10, <...>

sequence 惰性序列操作

println(people.asSequence()
            .map { it.name } //中间操作
            .filter { it.startsWith("A") } //中间操作
            .toList()) //末端操作
//找到第一个平方大于3的数,输出它的平方
println(listOf(1, 2, 3, 4).asSequence()
        .map { it * it }
        .find { it > 3 })

takeWhile

    val list = listOf(1, 2, 3, 4, 5, 6, 7, 9)
    list.takeWhile { it <= 3 }.forEach(::println)

解构声明

    val (c, ca) = "param=car=c".split("=").reversed()
    println("c=$c")
    println("ca=$ca")

foreach的坑

fun forEach0() {
    val list = listOf(1, 2, 3, 4)
    list.forEach {
        println("it=$it")
        if (it == 3) return //break不能在这里使用
    }
    println("Hello") //如果这样return, 将会执行不到这里
//>>>it=1
//>>>it=2
//>>>it=3
}

fun forEach1() {
    val list = listOf(1, 2, 3, 4)
    list.forEach block@{
        println("it=$it")
        if (it == 3) return@block //手动加标记  //lambda依然执行
    }
    println("Hello")
    //>>>it=1
    //>>>it=2
    //>>>it=3
    //>>>it=4
    //>>>Hello
}

fun forEach2() {
    val list = listOf(1, 2, 3, 4)
    list.forEach {
        println("it=$it")
        if (it == 3) return@forEach // forEach做为标记 //lambda依然执行
    }
    println("Hello")
    //>>>it=1
    //>>>it=2
    //>>>it=3
    //>>>it=4
    //>>>Hello
}


fun forEach3() {
    val list = listOf(1, 2, 3, 4)
    list.let {
        it.forEach {
            println("it=$it")
            if (it == 3) return@let //let方法做为标记 其他作用域函数皆可
        }
    }
    println("Hello")
    //>>>it=1
    //>>>it=2
    //>>>it=3
    //>>>Hello
}

fun forEach4() {
    val list = listOf(1, 2, 3, 4)
    fun a() {
        list.forEach {
            println("it=$it")
            if (it == 3) return@a //声明一个函数
        }
    }
    a()
    println("Hello")
    //>>>it=1
    //>>>it=2
    //>>>it=3
    //>>>Hello
}

你可能感兴趣的:(Kotlin集合内置函数)