美文网首页
Kotlin 集合常用API

Kotlin 集合常用API

作者: 改名_f64e | 来源:发表于2019-11-07 17:09 被阅读0次
    collections-diagram.png
           //只读,没有add,remove等方法
            val list1 = listOf<String>("one", "two", "three", "four", "five", "six")
            val set1 = setOf<String>("one", "two", "three", "four", "five", "six")
            val map1 = mapOf<String, Int>("one" to 1, "two" to 2)
            //可写  mutable
            val map2 = mutableMapOf<String, Int>().apply { this["one"] = 1;this["two"] = 2 }
    
            //空集合
            val emptyList = emptyList<String>()
            val emptySet = emptySet<String>()
            val emptyMap = emptyMap<String, Int>()
    
            //具体类型集合
            val arrayList: ArrayList<String>? = arrayListOf()
    
            //复制集合,副本和源数据不关联,删除副本集合数据,不影响源数据
            val copyList = arrayList?.toList()
    
            //集合遍历
    
            for ((key, value) in map1) {
                println("key = $key value = $value")
            }
            //API 24
    //        map1.forEach { key, value -> println("key = $key value = $value") }
    
            val iterator = list1.iterator()
    //        list1.listIterator()
            while (iterator.hasNext()) {
                val next = iterator.next()
            }
    
            for (index in list1.indices) {
                println("index = $index")
            }
            for (msg in list1) {
                println("msg = $msg")
            }
            list1.forEach { println(it) }
    
            //区间
            for (index in 0..10) {
                //[0,10]
                println("index = $index")
            }
            for (index in 0 until 10) {
                //[0,10)
                println("index = $index")
            }
            for (index in 0 until 10 step 2) {
                //[0,10) ,相当于 i=i+2 , 默认i++
                println("index = $index")
            }
            for (index in 10 downTo 1) {
                //[10,1] 倒序
                println("index = $index")
            }
            //map
            list1.mapIndexed { index, s -> println("index = $index msg = $s") }
            list1.mapIndexedNotNull { index, s -> println("index = $index msg = $s") }
            map1.mapKeys { println("key = ${it.key.toUpperCase()}") }
            map1.mapValues { println("key = ${it.value}") }
    
            //zip
            val colors = listOf("red", "brown", "grey")
            val animals = listOf("fox", "bear", "wolf")
            println(colors.zip(animals) { color, animal -> "The ${animal.capitalize()} is $color" })
            //[The Fox is red, The Bear is brown, The Wolf is grey]
    
            val numberPairs = listOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
            println(numberPairs.unzip())
            //([one, two, three, four], [1, 2, 3, 4])
    
            //joinToString()
            val numbers = listOf("one", "two", "three", "four")
    
            println(numbers)
            println(numbers.joinToString())
    
            val listString = StringBuffer("The list of numbers: ")
            numbers.joinTo(listString)
            println(listString)
            //[one, two, three, four]
            //one, two, three, four
            //The list of numbers: one, two, three, four
    
            val numbers2 = listOf("one", "two", "three", "four")
            println(numbers2.joinToString(separator = " | ", prefix = "start: ", postfix = ": end"))
            //start: one | two | three | four: end
    
            val numbers3 = (1..100).toList()
            println(numbers3.joinToString(limit = 10, truncated = "<...>"))
            //1, 2, 3, 4, 5, 6, 7, 8, 9, 10, <...>
    
            val numbers4 = listOf("one", "two", "three", "four")
            println(numbers4.joinToString { "Element: ${it.toUpperCase()}" })
            //Element: ONE, Element: TWO, Element: THREE, Element: FOUR
    
            //过滤
            val numbers5 = listOf("one", "two", "three", "four")
    
            val filteredIdx = numbers5.filterIndexed { index, s -> (index != 0) && (s.length < 5) }
            val filteredNot = numbers5.filterNot { it.length <= 3 }
            //[two, four]   filteredIdx
            //[three, four]  filteredNot 长度不大于3
    
            val numbers6 = listOf("one", "two", "three", "four")
            val (match, rest) = numbers6.partition { it.length > 3 }
            //[three, four]
            //[one, two]
    
            val numbers7 = listOf("one", "two", "three", "four")
    
            println(numbers7.any { it.endsWith("e") })//true,任何一个值以e结尾
            println(numbers7.none { it.endsWith("a") })//true,没有一个值以a结尾
            println(numbers7.all { it.endsWith("e") })//false,所有值都是以e结尾
    
            //分组
            val numbers8 = listOf("one", "two", "three", "four", "five")
            println(numbers8.groupBy(keySelector = { it.first() }, valueTransform = { it.toUpperCase() }))
            //{o=[ONE], t=[TWO, THREE], f=[FOUR, FIVE]}
            val numbers9 = listOf("one", "two", "three", "four", "five", "six")
            println(numbers9.groupingBy { it.first() }.eachCount())
            //{o=1, t=2, f=2, s=1}
    
            //取集合一部分
            //slice
            val numbers10 = listOf("one", "two", "three", "four", "five", "six")
            println(numbers10.slice(1..3))//[two, three, four]
            println(numbers10.slice(0..4 step 2))//[one, three, five]
            println(numbers10.slice(setOf(3, 5, 0)))//[four, six, one]
    
            //take drop
            val numbers11= listOf("one", "two", "three", "four", "five", "six")
            println(numbers11.take(3))//[one, two, three] 前三个  takeWhile 进行过滤
            println(numbers11.takeLast(3))//[four, five, six] 后三个
            println(numbers11.drop(1))//[two, three, four, five, six] 放弃第一个
            println(numbers11.dropLast(5))//[one] 从后往前数,放弃后面5个
    
            //chunked
            val numbers12 = (0..13).toList()
            println(numbers12.chunked(3))
            //[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13]]
            println(numbers12.chunked(3) { it.sum() })
            //[3, 12, 21, 30, 25]
    
            //windowed
            val numbers13 = listOf("one", "two", "three", "four", "five")
            println(numbers13.windowed(3))
            //[[one, two, three], [two, three, four], [three, four, five]]
    
            //zip
            println(numbers.zipWithNext())
            //[(one, two), (two, three), (three, four), (four, five)]
    
            //取单个元素
            val numbers14 = listOf("one", "two", "three", "four", "five")
            println(numbers.elementAt(3))//four,会抛出数组角标越界
            println(numbers14.elementAtOrNull(5))//null
            println(numbers14.elementAtOrElse(5) { index -> "The value for index $index is undefined"})
            //The value for index 5 is undefined
            //随机获取元素
            println(numbers.random())
            //是否存在 in contains()
    
            //排序,根据首字母自然排序
            val numbers15 = listOf("one", "two", "three", "four")
            println("Sorted ascending: ${numbers15.sorted()}")
            //Sorted ascending: [four, one, three, two]
    
            //自然排序倒序
            println("Sorted descending: ${numbers15.sortedDescending()}")
            //Sorted descending: [two, three, one, four]
    
            //自定义排序
            val sortedNumbers = numbers15.sortedBy { it.length }
            println("Sorted by length ascending: $sortedNumbers")
            //Sorted by length ascending: [one, two, four, three]
            val sortedByLast = numbers.sortedByDescending { it.last() }
            println("Sorted by the last letter descending: $sortedByLast")
            //Sorted by the last letter descending: [four, two, one, three] 根据尾字母倒序
    
            //倒序
            println(numbers.reversed())//[four, three, two, one]
            //随机排序
            println(numbers.shuffled())
    
            val numbers16 = mutableListOf("one", "two", "three", "four")
            val reversedNumbers = numbers16.asReversed()
            println(reversedNumbers)//[four, three, two, one]
            numbers16.add("five")
            println(reversedNumbers)//[five, four, three, two, one]
    
            //聚合操作
            val numbers17 = listOf(6, 42, 10, 4)
    
            println("Count: ${numbers17.count()}")//Count: 4
            println("Max: ${numbers17.max()}")//Max: 42
            println("Min: ${numbers17.min()}")//Min: 4
            println("Average: ${numbers17.average()}")//Average: 15.5
            println("Sum: ${numbers17.sum()}")//Sum: 62
    
            val numbers18 = listOf(5, 42, 10, 4)
            val min3Remainder = numbers18.minBy { it % 3 }
            println(min3Remainder)//42
    
            val strings = listOf("one", "two", "three", "four")
            val longestString = strings.maxWith(compareBy { it.length })
            println(longestString)//three
    
            val numbers19 = listOf(5, 42, 10, 4)
            println(numbers19.sumBy { it * 2 })//122
            println(numbers19.sumByDouble { it.toDouble() / 2 })//30.5
    

    相关文章

      网友评论

          本文标题:Kotlin 集合常用API

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