美文网首页
Kotlin中take、drop方法使用

Kotlin中take、drop方法使用

作者: 因为我的心 | 来源:发表于2022-05-31 11:34 被阅读0次

    1、 take方法:

    private fun take() {
        val mList = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
        //take函数是根据传入的参数挑出该集合【前n个元素】的子集合
        val mNewList1 = mList.take(2)
        println(mNewList1)
        //[1, 2]
    
        //takeLast函数是根据传入的参数挑出该集合【倒数n个元素】的子集合
        val mNewList2 = mList.takeLast(2)
        println(mNewList2)
        //[9, 0]
    }
    

    2、 takeWhile

    private fun takeWhile() {
        val mList = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
    
        //takeWhile : 从头开始取值,不符合立即停止
        val mNewList3 = mList.takeWhile {
            it % 2 == 0
        }
        println(mNewList3)
        //[]
    
    
        //takeLastWhile : 从尾开始取值,不符合立即停止
        val mNewList4 = mList.takeLastWhile {
            it % 2 == 0
        }
        println(mNewList4)
        //[0]
    }
    

    3、 takeIf

    private fun takeIf() {
        val mList = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
    
        //如果符合返回它
        val mNewList5 = mList.takeIf {
            it.size == 10 //true
        }
        println(mNewList5)
        //[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    
    
        val mNewList51 = mList.takeIf {
            it.size == 5  //false
        }
        println(mNewList51)
        //null
    }
    

    4、 takeUnless

    private fun takeUnless() {
        val mList = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
    
        //如果不符合返回它
        val mNewList6 = mList.takeUnless {
            it.size == 10  //true
        }
        println(mNewList6)
        //null
    
    
        val mNewList61 = mList.takeUnless {
            it.size == 5  //false
        }
        println(mNewList61)
        //[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    
    }
    

    5、 drop

    private fun drop() {
        //去掉前n个开始取值
        val mList = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
        val resultList = mList.drop(3)
        println(resultList)
    }
    //[4, 5, 6, 7, 8, 9, 0]
    

    6、 dropLast

    private fun dropLast() {
        //去掉最后n个开始取值
        val mList = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
        val resultList = mList.dropLast(3)
        println(resultList)
    }
    //[1, 2, 3, 4, 5, 6, 7]
    

    7、dropLastWhile

    private fun dropWhile() {
        //从头开始找不满足的开始取值,满足的抛弃头部
        val mList = mutableListOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
        val resultList = mList.dropWhile { it <= 1 }
        println(resultList)
    }
    //[2, 3, 4, 5, 6, 7, 8, 9, 0]
    
    

    链接:https://blog.csdn.net/sinat_31057219/article/details/105996133

    相关文章

      网友评论

          本文标题:Kotlin中take、drop方法使用

          本文链接:https://www.haomeiwen.com/subject/iwlzprtx.html