Kotlin 函数式API apply和filterTo的使用

直接看代码

fun main(){
    val numberList1 = listOf(23, 65, 14, 57, 99, 123, 26, 15, 88, 37, 56)
    val numberList2 = listOf(13, 55, 24, 67, 93, 137, 216, 115, 828, 317, 16)
    val numberList3 = listOf(20, 45, 19, 7, 9, 3, 26, 5, 38, 75, 46)
    
    val oddNumberList = mutableListOf<Int>()
    numberList1.filterTo(oddNumberList) {
        it % 2 == 1
    }
    numberList2.filterTo(oddNumberList) {
        it % 2 == 1
    }
    numberList3.filterTo(oddNumberList) {
        it % 2 == 1
    }
    
    //需要注意一点的是,我们从源码看到filterTo第一个参数destination是一个可变集合类型,所以这里使用的mutableListOf初始化
    val evenNumberList = mutableListOf<Int>().apply {
        numberList1.filterTo(this) {
            it % 2 == 0
        }
        numberList2.filterTo(this) {
            it % 2 == 0
        }
        numberList3.filterTo(this) {
            it % 2 == 0
        }
    }
    
    print("从三个集合筛选出的奇数集合: \n")
    oddNumberList.forEach {
        print("$it   ")
    }
    println("\n")

    print("从三个集合筛选出的偶数集合: \n")
    evenNumberList.forEach {
        print("$it   ")
    }
    println("\n")

}
打印结果.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容