美文网首页
Collections

Collections

作者: yesyourhighness | 来源:发表于2019-12-17 11:22 被阅读0次

    Kotlin lets you manipulate collections independently of the exact type of objects stored in them. In other words, you add a String to a list of Strings the same way as you would do with Ints or a user-defined class. So, the Kotlin Standard Library offers generic interfaces, classes, and functions for creating, populating, and managing collections of any type.

    val numbers = mutableListOf("one", "two", "three", "four")
    numbers.add("five")   // this is OK    
    //numbers = mutableListOf("six", "seven")   
    

    只读集合是型变的,可变集合不是型变的
    在 Kotlin 中,List 的默认实现是 ArrayList,可以将其视为可调整大小的数组

    • 注意,to 符号创建了一个短时存活的 Pair 对象,因此建议仅在性能不重要时才使用它。 为避免过多的内存使用,请使用其他方法

    可以通过其他集合各种操作的结果来创建集合

    1. 过滤filter() filterIndexed() filterNot() filterIsInstance() filterNotNull() partition() 检验谓词 any() none() all()
    val numbers = listOf("one", "two", "three", "four")
    println(numbers.any { it.endsWith("e") })
    println(numbers.none { it.endsWith("a") })
    println(numbers.all { it.endsWith("e") })
    
    println(emptyList<Int>().all { it > 5 })   // vacuous truth
    
    1. 映射 map mapIndexed mapNotNull mapIndexedNotNull mapKeys mapValues
    2. 关联 associateWith associateBy() 区别:building maps with collection elements as keys/values
    3. 分组 groupBy()
      5 slice() take() drop() takeWhile()
      6.取单个元素 elementAt() first() last() elementAtOrNull()

    双路合并(zip)

    val colors = listOf("red", "brown", "grey")
    val animals = listOf("fox", "bear", "wolf")
    println(colors zip animals)
    
    val twoAnimals = listOf("fox", "bear")
    println(colors.zip(twoAnimals))
    

    集合排序
    Most built-in types are comparable: 自定义类型如何排序?
    A shorter way to define a Comparator is the compareBy() standard library.
    The Kotlin collections package provides functions for sorting collections in natural, custom, and even random orders.
    sort read-only collections and sorting mutable collections difference?
    sortedBy() sortedWith()
    reversed() 返回一个集合(原元素的拷贝),偏好使用asReversed(),如果原集合不变的话.但是,如果如果list的可变行不知道或者原集合就不是list,推荐使用reversed().
    随机顺序 shuffled()

    集合写操作
    add() addAll() += remvove() removeAll() retainAll() clear() -=(single instance remove the first occurrence of it)

    val numbers = mutableListOf("one", "two", "three", "three", "four")
    numbers -= "three"
    println(numbers)
    numbers -= listOf("four", "five")    
    //numbers -= listOf("four")    // does the same as above
    println(numbers)    
    

    list的操作
    getOrElse() getOrNull subList() indexOf() indexOfFirst() binarySearch()
    add() addAll() set() fill() removeAt()
    set
    map plus minus操作

    相关文章

      网友评论

          本文标题:Collections

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