美文网首页kotlin
kotlin 中 Collection 相关操作

kotlin 中 Collection 相关操作

作者: 星月下的青草 | 来源:发表于2019-03-20 22:32 被阅读0次

    filter

    filter 函数让您可以过滤集合。它将过滤谓词作为lambda参数。谓词应用于每个元素。使谓词为true的元素将在结果集合中返回。

    简单来说就是在filter 函数中设置你需要集合满足的条件,然后返回满足条件的元素。

    eg:

    
    fun filterTest() {
        val numbers = listOf(1, 2, 3, 4, 5, 6, -1, -3, -4)
        val positive = numbers.filter {
            it > 0
        }
        println(positive.toString())
    
        val negatives = numbers.filter { a -> a < 0 }
        println(negatives.toString())
    }
    
    

    输出结果:

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

    map

    通过映射扩展功能,您可以将转换应用于集合中的所有元素。它将变压器功能作为lambda参数。

    eg:

    
    fun mapTest() {
        val numbers = listOf(1, 2, 3, 4, 5, 6, -1, -3, -4)
        val map = numbers.map {
            it * 3
        }
        println(map.toString())
    }
    

    打印结果:

    
    [3, 6, 9, 12, 15, 18, -3, -9, -12]
    
    

    any, all, none

    作用:检查是否存在与给定条件匹配的集合元素。

    any

    如果集合包含至少一个与给定条件匹配的元素,则函数any返回true。

    eg:

    
    fun anyTest() {
        val numbers = listOf(1, -2, 3, -4, 5, -6)            // 1
    
        val anyNegative = numbers.any { it < 0 }             // 2
    
        val anyGT6 = numbers.any { it > 6 }
    
        println("Is there any number less than 0: $anyNegative")
        println("Is there any number greater than 6: $anyGT6")
    }
    
    

    输出结果:

    
    Is there any number less than 0: true
    
    Is there any number greater than 6: false
    
    

    all

    如果集合中的所有元素都与给定的条件匹配,则函数all返回true。

    eg:

    
    fun allTest() {
        val numbers = listOf(1, -2, 3, -4, 5, -6)            // 1
    
        val allEven = numbers.all { it % 2 == 0 }            // 2
    
        val allLess6 = numbers.all { it < 6 }
    
        println("All numbers are even: $allEven")
        println("All numbers are less than 6: $allLess6")
    }
    
    

    输出结果:

    
    All numbers are even: false
    
    All numbers are less than 6: true
    
    

    none

    如果没有与集合中给定条件匹配的元素,则函数none返回true。

    eg:

    
    fun noneTest() {
        val numbers = listOf(1, -2, 3, -4, 5, -6)            // 1
    
        val allEven = numbers.none { it % 2 == 1 }            // 2
    
        val allLess6 = numbers.none { it > 6 }
    
        println("All numbers are even: $allEven")
        println("No element greater than 6: $allLess6")
    }
    
    

    输出结果:

    
    All numbers are even: false 
    
    No element greater than 6: true
    
    

    find findLast fisrt last

    findfindLast函数返回与给定条件匹配的第一个或最后一个集合元素。如果没有这样的元素,函数返回null。

    例子:find findLast

    
    fun findTest() {
    
        val words = listOf("Lets", "find", "something", "in", "collection", "somehow")  // 1
    
        val first = words.find { it.startsWith("some") }                                // 2
        val last = words.findLast { it.startsWith("some") }                             // 3
    
        val nothing = words.find { it.contains("nothing") }                             // 4
    
        println("The first word starting with \"some\" is $first")
        println("The last word starting with \"some\" is $last")
        println("The first word containing \"nothing\" is $nothing")
    }
    
    

    输出结果:

    
    The first word starting with "some" is something
    
    The last word starting with "some" is somehow
    
    The first word containing "nothing" is null
    
    

    注意:它输出的是满足条件的以一个或者最后一个,不是集合中的第一个或最后一个

    fisrt 和 **last ** 返回集合第一个和最后一个元素,也可以为其添加条件

    例子: fisrt last

    
    val numbers = listOf(1, -2, 3, -4, 5, -6) // 1
    
    
    
    val first = numbers.first() // 2
    
    val last = numbers.last() // 3
    
    
    
    val firstEven = numbers.first { it % 2 == 0 } // 4
    
    val lastOdd = numbers.last { it % 2 != 0 } // 5
    
    

    输出结果:

    
    Numbers: [1, -2, 3, -4, 5, -6] 
    
    First 1, last -6, first even -2, last odd 5
    
    

    count

    返回集合个数,或者满足一定条件的元素个数

    
    val numbers = listOf(1, -2, 3, -4, 5, -6)            // 1
    
    val totalCount = numbers.count()                     // 2
    val evenCount = numbers.count { it % 2 == 0 }        // 3
    
    输出结果:
    Total number of elements: 6
    Number of even elements: 3
    
    

    partition

    函数的功能是把原来的集合根据给定的条件拆分成两个列表,满足条件

    
    fun partitionTest() {
        val numbers = listOf(1, -2, 3, -4, 5, -6)                // 1
    
        val evenOdd = numbers.partition { it % 2 == 0 }           // 2
        val (positives, negatives) = numbers.partition { it > 0 } // 3
    
        println("奇偶:$evenOdd")
        println("偶数:${evenOdd.first}")
        println("奇数 :${evenOdd.second}")
        println("positives : $positives")
        println("negatives : $negatives")
    }
    

    输出结果:

    
    奇偶:([-2, -4, -6], [1, 3, 5])
    
    偶数:[-2, -4, -6]
    
    奇数 :[1, 3, 5]
    
    positives : [1, 3, 5]
    
    negatives : [-2, -4, -6]
    
    

    associateBy, groupBy

    函数associateBy和groupBy构建来自由指定键索引的集合的元素的映射。key在keySelector参数中定义。

    您还可以指定可选的valueSelector来定义将存储在map元素值中的内容。

    区别

    associateBy和groupBy之间的区别在于它们如何使用相同的键处理对象:

    • associateBy使用最后一个合适的元素作为值。

    • groupBy构建所有合适元素的列表并将其放入值中。

    
    fun associateTest() {
        data class Person(val name: String, val city: String, val phone: String)            //1
    
        val people = listOf(                                                     // 2
            Person("John", "Boston", "+1-888-123456"),
            Person("Sarah", "Munich", "+49-777-789123"),
            Person("Svyatoslav", "Saint-Petersburg", "+7-999-456789"),
            Person("Vasilisa", "Saint-Petersburg", "+7-999-123456")
        )
    
        val phoneBook = people.associateBy { it.phone }                          // 3
        val cityBook = people.associateBy(Person::phone, Person::city)           // 4
        val cityBook222 = people.associateBy(Person::city, Person::name)           // 4
        val peopleCities = people.groupBy(Person::city, Person::name)            // 5
    
    
        println("people:$people")
        println("phoneBook:$phoneBook")
        println("cityBook222:$cityBook222")
        println("cityBook:$cityBook")
        println("peopleCities:$peopleCities")
    
    }
    
    

    输出结果:

    
    people:[Person(name=John, city=Boston, phone=+1-888-123456), Person(name=Sarah, city=Munich, phone=+49-777-789123), Person(name=Svyatoslav, city=Saint-Petersburg, phone=+7-999-456789), Person(name=Vasilisa, city=Saint-Petersburg, phone=+7-999-123456)]
    
    
    
    phoneBook:{+1-888-123456=Person(name=John, city=Boston, phone=+1-888-123456), +49-777-789123=Person(name=Sarah, city=Munich, phone=+49-777-789123), +7-999-456789=Person(name=Svyatoslav, city=Saint-Petersburg, phone=+7-999-456789), +7-999-123456=Person(name=Vasilisa, city=Saint-Petersburg, phone=+7-999-123456)}
    
    
    
    cityBook222:{Boston=John, Munich=Sarah, Saint-Petersburg=Vasilisa}
    
    
    
    cityBook:{+1-888-123456=Boston, +49-777-789123=Munich, +7-999-456789=Saint-Petersburg, +7-999-123456=Saint-Petersburg}
    
    
    
    peopleCities:{Boston=[John], Munich=[Sarah], Saint-Petersburg=[Svyatoslav, Vasilisa]}
    
    
    
    

    我们可以从输出结果中看到 通过city 作为key的时候 ,两种方式对相同key的处理

    zip

    zip函数将两个给定的集合合并到一个新集合中。默认情况下,结果集合包含具有相同索引的成对源集合元素。但是,您可以定义结果集合元素的自己的结构。

    
    fun main() {
    
    
    
        val A = listOf("a", "b", "c","d","e") // 1
    
        val B = listOf(1, 2, 3, 4) // 1
    
    
    
        val resultPairs = A zip B // 2
    
        val resultReduce = A.zip(B) { a, b -> "$a$b" } // 3
    
    
    
        println("A to B: $resultPairs")
    
        println("\$A\$B: $resultReduce")
    
    }
    
    

    输出结果:

    
    A to B: [(a, 1), (b, 2), (c, 3), (d, 4)] 
    
    $A$B: [a1, b2, c3, d4]
    
    

    flatMap

    flatMap将集合的每个元素转换为可迭代对象,并构建转换结果的单个列表。转换是用户定义的。

    
    fun main() {
    
    
    
        val numbers = listOf(1, 2, 3) // 1
    
    
    
        val tripled = numbers.flatMap { 
    
            listOf(it+1) } // 2
    
    
    
        println("Numbers: $numbers")
    
        println("Transformed: $tripled")
    
    }
    
    

    输出结果:

    
    Numbers: [1, 2, 3] 
    
    Transformed: [2, 3, 4]
    
    

    min,max

    min和max函数返回集合中最小和最大的元素。如果集合为空,则返回null。

    
    fun main() {
    
    
    
        val numbers = listOf(1, 2, 3)
    
        val empty = emptyList<Int>()
    
    
    
        println("Numbers: $numbers, min = ${numbers.min()} max = ${numbers.max()}") // 1
    
        println("Empty: $empty, min = ${empty.min()}, max = ${empty.max()}") // 2
    
    }
    
    

    输出结果 :

    
    Numbers: [1, 2, 3], min = 1 max = 3 
    
    Empty: [], min = null, max = null
    
    

    sorted sortedBy

    sorted :返回根据其自然排序顺序(升序)排序的集合元素列表。

    sortedBy:根据指定选择器函数返回的值的自然排序顺序对元素进行排序。

    
    fun main() {
    
    
    
        val shuffled = listOf(5, 4, 2, 1, 3) // 1
    
        val natural = shuffled.sorted() // 2
    
        val inverted = shuffled.sortedBy { -it } // 3
    
    
    
        println("Shuffled: $shuffled")
    
        println("Natural order: $natural")
    
        println("Inverted natural order: $inverted")
    
    }
    
    

    输出结果:

    
    Shuffled: [5, 4, 2, 1, 3] 
    
    Natural order: [1, 2, 3, 4, 5] 
    
    Inverted natural order: [5, 4, 3, 2, 1]
    
    

    getOrElse

    提供对集合元素的安全访问。它采用索引和函数,在索引超出范围时提供默认值。

    
    fun main() {
    
        val list = listOf(0, 10, 20)
    
        println(list.getOrElse(1) { 42 }) // 1
    
        println(list.getOrElse(10) { 42 }) // 2
    
    }
    
    

    输出结果:

    
    10 
    
    42
    
    

    Map Element Access

    应用于map时,[]运算符返回与给定键对应的值,如果map中没有此类键,则返回null。

    getValue函数返回与给定键对应的现有值,如果未找到该键则抛出异常。对于使用withDefault创建的映射,getValue返回默认值而不是抛出异常。

    
    fun main(args: Array<String>) {
    
    
    
        val map = mapOf("key" to 42)
    
    
    
        val value1 = map["key"] // 1
    
        val value2 = map["key2"] // 2
    
    
    
        val value3: Int = map.getValue("key") // 1
    
    
    
        val mapWithDefault = map.withDefault { k -> k.length }
    
        val value4 = mapWithDefault.getValue("key2") // 3
    
    
    
        try {
    
            map.getValue("anotherKey") // 4
    
        }
    
        catch (e: NoSuchElementException) {
    
            println("Message: $e")
    
        }
    
    
    
    
    
        println("value1 is $value1")
    
        println("value2 is $value2")
    
        println("value3 is $value3")
    
        println("value4 is $value4")
    
    }
    
    

    输出结果:

    
    Message: java.util.NoSuchElementException: Key anotherKey is missing in the map. 
    
    value1 is 42 
    
    value2 is null 
    
    value3 is 42 
    
    value4 is 4
    
    

    相关文章

      网友评论

        本文标题:kotlin 中 Collection 相关操作

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