前言
集合是一个大头,经常会碰到。
所以,我做了一个集锦。看起来会比较长,所以,我做了一些取舍。尽量缩短,又可以了解清楚。
这部分的内容,大部分语言都会涉及。有些地方就不放开详述。
文章定位你可以大体了解有哪些。大致怎么用。
用到的时候,完全可以查一下就知道了。
目录如下
- set、list以及map
- 创建
- 迭代器
- 序列化处理
- 过滤
- 集合的加减
- 分组
- 取集合的一部分
- 取单个元素
- 排序
- 聚合操作
- 集合写操作
- list
- Set
- Map
set、list 以及 map
这图太棒了。基本就把Kotlin中的集合说个框架了。
主要分为mutable可变、跟非可变
创建
大致格式就是这样。
listOf()、setOf()、mutableListOf()、mutableSetOf()
范例
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
val numbersSet = setOf("one", "two", "three", "four")
空集合
emptyList()、emptySet() 与 emptyMap()
迭代器
跟java基本上是差不多的。之前的Kotlin入门中,也讲到过。就不详述了。每个部分,给范例大致看一下。
iterator
看下范例,就清楚了,其他语言你很可能碰到过了
val numbers = listOf("one", "two", "three", "four")
val numbersIterator = numbers.iterator()
while (numbersIterator.hasNext()) {
println(numbersIterator.next())
}
for…in
看下范例,就清楚了,其他语言你很可能碰到过了
val numbers = listOf("one", "two", "three", "four")
for (item in numbers) {
println(item)
}
forEach
看下范例,就清楚了,其他语言你很可能碰到过了
val numbers = listOf("one", "two", "three", "four")
numbers.forEach {
println(it)
}
分为可变迭代器和非可变迭代器
怎么区分呢
可从字面上了解,如果mutableXXXXOf
那么调用iterator得到的 -> 就是可变的iterator
so Easy》。。。。。
序列化处理
可以用sequenceOf得到序列化
可以单个操作
看下范例,就清楚了,其他语言你很可能碰到过了
val numbers = listOf("one", "two", "three", "four")
val numbersSequence = numbers.asSequence()
也可以块级操作
看下范例,就清楚了,其他语言你很可能碰到过了
val oddNumbers = sequence {
yield(1)
yieldAll(listOf(3, 5))
yieldAll(generateSequence(7) { it + 2 })
}
println(oddNumbers.take(5).toList())
过滤
区分
看下范例,就清楚了,其他语言你很可能碰到过了
看范例一
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}
println(filteredMap)
看范例二
val numbers = listOf("one", "two", "three", "four")
val filteredIdx = numbers.filterIndexed { index, s -> (index != 0) && (s.length < 5) }
val filteredNot = numbers.filterNot { it.length <= 3 }
println(filteredIdx)
println(filteredNot)
这里用的是filter函数
划分
看下范例,就清楚了
val numbers = listOf("one", "two", "three", "four")
val (match, rest) = numbers.partition { it.length > 3 }
println(match)
println(rest)
这里用的是partition
检验谓词
- any()
有一个为true即返回true - none()
一个都不匹配返回true - all()
所有都匹配返回true
集合的加减
看下范例,就清楚了
val numbers = listOf("one", "two", "three", "four")
val plusList = numbers + "five"
val minusList = numbers - listOf("three", "four")
println(plusList)
println(minusList)
输出结果
one, two, three, four, five]
[one, two]
集合可以这么进行加减,按照推导的原理,的确可以这么做。符合逻辑。于是kotlin便支持了。只是这里的 集合添加删除 单个\多个collection进一步被简化。
分组
groupBy
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.groupBy { it.first().toUpperCase() })
println(numbers.groupBy(keySelector = { it.first() }, valueTransform = { it.toUpperCase() }))
输出结果
{O=[one], T=[two, three], F=[four, five]}
{o=[ONE], t=[TWO, THREE], f=[FOUR, FIVE]}
操作类型
- eachCount()
统计计数 - fold() and reduce()
将每个分组当成独立的分组进行计算 - aggregate()
通过一个函数(operation)混合每种分类中每个元素的结果
这是通用方法
可以提供自定义操作
取集合的一部分
slice()
从某个位置开始得到新集合,js也有这个操作。
take(3)、takeLast(3)、drop(3)、Last(3)、takeWhile(3)、takeLastWhile(3)、dropWhile()、dropLastWhile
fun main() {
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.takeWhile { !it.startsWith('f') })
println(numbers.takeLastWhile { it != "three" })
println(numbers.dropWhile { it.length == 3 })
println(numbers.dropLastWhile { it.contains('i') })
}
输出结果
[one, two, three]
[four, five, six]
[three, four, five, six]
[one, two, three, four]
chunked
截取头几个element
windowed
得到多个数组。每几个element组成一个collection
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.windowed(3))
输出结果
[[one, two, three], [two, three, four], [three, four, five]]
支持
- step 步长
- partialWindows
范例二
val numbers = (1..10).toList()
println(numbers.windowed(3, step = 2, partialWindows = true))
println(numbers.windowed(3) { it.sum() })
输出结果
[[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, 10]]
[6, 9, 12, 15, 18, 21, 24, 27]
zipWithNext
跟隔壁的element打包
fun main() {
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.zipWithNext())
println(numbers.zipWithNext() { s1, s2 -> s1.length > s2.length})
}
输出结果
[(one, two), (two, three), (three, four), (four, five)]
[false, false, true, false]
取单个元素
按位置取
elementAt
取第一个或最后一个
first()
last()
取不到怎么处理
elementAtOrNull()
elementAtOrElse()
fun main() {
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.elementAtOrNull(5))
println(numbers.elementAtOrElse(5) { index -> "The value for index $index is undefined"})
}
输出结果
null
The value for index 5 is undefined
按条件取
范例
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.first { it.length > 3 })
println(numbers.last { it.startsWith("f") })
输出结果
three
fiv
find()
fun main() {
val numbers = listOf(1, 2, 3, 4)
println(numbers.find { it % 2 == 0 })
println(numbers.findLast { it % 2 == 0 })
}
输出结果
2
4
随机取元素
val numbers = listOf(1, 2, 3, 4)
println(numbers.random())
判断是否存在
contains
排序
这一块基本就是copy JavaScript的
- sorted()
- sortedDescending()
- 自定义
- sortedBy { it.length } - 倒序
- reversed() - 随机
- shuffled()
聚合操作
就是对整体collection进行操作
- min() and max()
返回最大或最小值 - average()
返回所有值的平均值 - sum()
返回所有值的和 - count()
进行统计计数 - fold()\reduce()
会使用初始值进行操作
看范例,再理解一下
fun main() {
val numbers = listOf(5, 2, 10, 4)
val sum = numbers.reduce { sum, element -> sum + element }
println(sum) // 21
val sumDoubled = numbers.fold(2) { sum, element -> sum + element * 3 }
println(sumDoubled) // 65
}
集合写操作
add()
remove()
list
取单个值
get(0)
getOrNull(5)
getOrElse(5, {it})
取列表的一部分
subList(3, 6)
查找元素位置
indexOf(2)
lastIndexOf(2)
indexOfFirst { it > 2}
indexOfLast { it % 2 == 1}
有序列表中二分查找
binarySearch
Comparator 二分搜索
val productList = listOf(
Product("WebStorm", 49.0),
Product("AppCode", 99.0),
Product("DotTrace", 129.0),
Product("ReSharper", 149.0))
println(productList.binarySearch(Product("AppCode", 99.0), compareBy<Product> { it.price }.thenBy { it.name }))
输出结果
1
比较函数二分搜索
binarySearch { priceComparison(it, 99.0) }
List 写操作
- add
- remove
- fill
- sort()
- sortDescending
- sortBy
- shuffle
- reverse
- asReversed
Set
- union()
将两个collections合并 - intersect()
在当前数组中找 目标元素,找到后返回该元素 - subtract()
在当前数组中,找 不是目标元素 的元素,找到后返回
Map
- 取值
get()
getValue
getOrElse
getOrDefault - 过滤
filter
这里就不在详述了 - plus和minus操作
根据 key值,进行Map数组的元素的加减
fun main() {
val numbersMap = mapOf("one" to 1, "two" to 2, "three" to 3)
println(numbersMap + Pair("four", 4))
println(numbersMap + Pair("one", 10))
println(numbersMap + mapOf("five" to 5, "one" to 11))
}
输出结果
{one=1, two=2, three=3, four=4}
{one=10, two=2, three=3}
{one=11, two=2, three=3, five=5}
- 写操作
- putAll
- put
- remove
小结
Kotlin在集合这部分,借鉴了JS在这方面的便捷性,增强了基本的API。