Kotlin的集合类虽然继承自Java,但是增加了更多能力,使用更具优势
immutable
和mutable
两类,默认的immutable类型使用起来更安全listOf
,setOf
等filter()
等List
、Set
、Map
等常用集合类的继承体系与JDK基本一样,只是接口类型默认是immutable的,没有定义用于改变集合对象的“写”方法。可写的集合类需要通过另一套MutableXXX
接口实现
Kotlin中调用Java代码时,集合类会自动转换,
例如 java.util.Iterator
转换为kotlin.collection.Iterator
,
因此,即使Java集合类对象也可以使用Kotlin集合操作符进行操作
Kotlin鼓励使用工厂模式创建集合,提供了多种工厂放阿飞
val list = listOf(1, 2, 3)
val map = mapOf("foo" to "FOO", "bar" to "BAR")
val set = setOf(9, 8, 7)
1.4新增了创建不含有null的集合的listOfNotNull
fun main(args: Array<String>) {
val list = listOf(null, 1, 2, 3, null)
val notNullList = listOfNotNull(null, 1, 2, 3, null)
println(list)
println(notNullList)
}
#运行结果
[null, 1, 2, 3, null]
[1, 2, 3]
val list = mutableListOf(1, 2, 3)
val map = mutableMapOf("foo" to "FOO", "bar" to "BAR")
val set = mutableSetOf(9, 8, 7)
对Java的各集合类型也提供了工厂方法,但因为创建的对象都是mutable的,所以并不推荐使用。
fun main(args: Array<String>) {
printClass("arrayListOf", arrayListOf<Int>())
printClass("hashSetOf", hashSetOf<Int>())
printClass("linkedSetOf", linkedSetOf<Int>())
printClass("sortedSetOf", sortedSetOf<Int>())
printClass("hashMapOf", hashMapOf<Int, Int>())
printClass("linkedMapOf", linkedMapOf<Int, Int>())
printClass("sortedMapOf", sortedMapOf<Int, Int>())
}
fun printClass(functionName: String, collection: Any) {
println("$functionName = ${collection.javaClass}")
}
# 结果
arrayListOf = class java.util.ArrayList
hashSetOf = class java.util.HashSet
linkedSetOf = class java.util.LinkedHashSet
sortedSetOf = class java.util.TreeSet
hashMapOf = class java.util.HashMap
linkedMapOf = class java.util.LinkedHashMap
sortedMapOf = class java.util.TreeMap
indices
是index
的复数形式。
顾名思义,其存储着Array或Collection中index的IntRange
fun main(args: Array<String>) {
val list = listOf(1, 2, 3)
val indices: IntRange = list.indices
println(indices)
for (i in list.indices) {
println(list[i])
}
}
#结果
0..2
1
2
3
最后一个元素的index,相当于size-1
fun main(args: Array<String>) {
val list = listOf(1, 2, 3)
println(list.lastIndex)
}
#结果
2
Kotlin集合操作符数量众多,基本上可以覆盖StreamAPI的所有功能
Steam | Kotlin |
---|---|
Stream.allMatch() | Iterable.all(), Map.all() |
Stream.anyMatch() | Iterable.any(), Map.any() |
Stream.count() | Iterable.count(), Map.count() |
Stream.distinct() | Iterable.distinct() |
Stream.filter() | Iterable.filter(), Map.filter() |
Stream.findFirst() | Iterable.first(), Iterable.firstOrNull() |
Stream.flatMap() | Iterable.flatMap(), Map.flatMap() |
Stream.forEach() | Iterable.forEach(), Map.forEach() |
Stream.limit() | Iterable.take() |
Stream.map() | Iterable.map(), Map.map() |
Stream.max() | Iterable.max(), Map.maxBy() |
Stream.min() | Iterable.min(), Map.minBy() |
Stream.noneMatch() | Iterable.none(), Map.none() |
Stream.peek() | – |
Stream.reduce() | Iterable.reduce() |
Stream.sorted() | Iterable.sorted() |
Stream.skip() | – |
Stream.collect(toList()) | Iterable.toList(), Map.toList() |
Stream.collect(toMap()) | Iterable.toMap() |
Stream.collect(toSet()) | Iterable.toSet() |
Stream.collect(joining()) | Iterable.joinToString() |
Stream.collect(partitioningBy()) | Iterable.partition() |
Stream.collect(groupingBy()) | Iterable.groupBy() |
Stream.collect(reducing()) | Iterable.fold() |
IntStream.sum() | Iterable.sum() |
IntStream.average() | Iterable.average() |
接下来,根据Interface分别介绍各操作符的使用:
所有元素均命中判断条件,返回true
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
println(iterable.all { it < 4 })
println(iterable.all { it < 3 })
}
true
false
任意元素命中判断条件,返回true
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
println(iterable.any { it < 4 })
println(iterable.any { it < 0 })
}
true
false
集合转为map,元素为key
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
val map = iterable.associate { it to it*10 }
println(map)
}
{1=10, 2=20, 3=30}
集合转为Map
,元素为value
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
val map = iterable.associateBy { it*10 }
println(map)
}
{10=1, 20=2, 30=3}
元素平均值。元素类型必须为Integer
、Float
等数字类型
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
val average = iterable.average()
println(average)
}
2.0
判断是否含有指定元素
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
println(iterable.contains(2))
println(iterable.contains(4))
}
true
false
元素个数 or 满足lambda条件的元素个数
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
println(iterable.count())
println(iterable.count {it % 2 == 1})
}
3
2
去重
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 1, 2, 2, 3, 1, 3)
println(iterable.distinct())
}
[1, 2, 3]
根据lambda去重
fun main(args: Array<String>) {
val iterable = listOf("foo", "bar", "fizz", "buzz", "hoge")
println(iterable.distinctBy { it.length })
}
[foo, fizz]
丢弃某元素
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.drop(2))
}
[3, 4, 5]
根据lambda丢弃元素
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.dropWhile { it != 4 })
}
[4, 5]
获取指定元素,参数非法时会IndexOutOfBoundsException
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.elementAt(2))
}
3
获取指定元素,参数非法时返回lambda的结果
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
println(iterable.elementAtOrElse(0, { it * 10 }))
println(iterable.elementAtOrElse(5, { it * 10 }))
}
1
50
获取指定元素,参数非法时返回null
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
println(iterable.elementAtOrNull(0))
println(iterable.elementAtOrNull(5))
}
1
null
lambda条件过滤
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
println(iterable.filter { it % 2 != 0 })
}
[1, 3]
过滤指定类型的元素
fun main(args: Array<String>) {
val iterable: Iterable<*> = listOf(1, "foo", 2.4, false)
println(iterable.filterIsInstance<Number>())
println(iterable.filterIsInstance(String::class.java))
}
[1, 2.4]
抛弃符合条件的元素
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.filterNot { it % 2 == 0 })
}
[1, 3, 5]
过滤非空元素
fun main(args: Array<String>) {
val iterable = listOf(1, null, 3, null, 5)
println(iterable.filterNotNull())
}
[1, 3, 5]
第一个符合条件的元素,等价于 firstOrNull()
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.find { it % 2 == 0 })
println(iterable.find { it % 6 == 0 })
}
2
null
从后往前第一个符合条件的元素,等价于lastOrNull()
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.findLast { it % 2 == 0 })
println(iterable.findLast { it % 6 == 0 })
}
4
null
第一个符合条件的元素,找不到返回异常
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.first())
println(iterable.first { it % 2 == 0 })
println(iterable.first { it % 6 == 0 })
}
1
2
Exception in thread "main" java.util.NoSuchElementException: No element matching predicate was found.
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.firstOrNull())
println(iterable.firstOrNull { it % 2 == 0 })
println(iterable.firstOrNull { it % 6 == 0 })
}
1
2
null
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.last())
println(iterable.last { it % 2 == 0 })
println(iterable.last { it % 6 == 0 })
}
5
4
Exception in thread "main" java.util.NoSuchElementException: No element matching predicate was found.
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.lastOrNull())
println(iterable.lastOrNull { it % 2 == 0 })
println(iterable.lastOrNull { it % 6 == 0 })
}
5
4
null
连接多个Iterable
fun main(args: Array<String>) {
val iterable: Iterable<Iterable<Int>> = listOf(
listOf(1, 2, 3),
listOf(4, 5, 6),
listOf(7, 8, 9)
)
println(iterable.flatMap { it })
}
[1, 2, 3, 4, 5, 6, 7, 8, 9]
拍平子Iterable
fun main(args: Array<String>) {
val iterable: Iterable<Iterable<Int>> = listOf(
listOf(1, 2, 3),
listOf(4, 5, 6),
listOf(7, 8, 9)
)
println(iterable.flatten())
}
[1, 2, 3, 4, 5, 6, 7, 8, 9]
对每个元素逐个执行lambda运算,运算结果作为下次运算的输入。
第一个参数为启动输入
fun main(args: Array<String>) {
val iterable = listOf("a", "b", "c")
println(iterable.fold("Z", { buf, value -> buf + value }))
}
Zabc
循环遍历
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
iterable.forEach { println(it) }
}
1
2
3
根据条件分组
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5, 6, 7)
val result1: Map<String, List<Int>> =
iterable.groupBy { if (it % 2 == 0) "偶数" else "奇数" }
println(result1)
val result2: Map<String, List<String>> =
iterable.groupBy(
{ if (it % 2 == 0) "偶数" else "奇数" },
{ "<$it>"}
)
println(result2)
}
{奇数=[1, 3, 5, 7], 偶数=[2, 4, 6]}
{奇数=[<1>, <3>, <5>, <7>], 偶数=[<2>, <4>, <6>]}
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.indexOfFirst { it % 2 == 0 })
}
1
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.indexOfLast { it % 2 == 0 })
}
3
去重后返回Set
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
val other = listOf(2, 3, 5, 2)
val result: Set<Int> = iterable.intersect(other)
println(result)
}
[2, 3, 5]
将集合以字符串输出,可以通过Appendable
指定元素的连接格式,默认是半角逗号
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
val buffer: Appendable = StringBuilder()
iterable.joinTo(buffer)
println(buffer)
}
1, 2, 3, 4, 5
可以通过更多参数,指定更复杂的连接格式
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
val buffer: Appendable = StringBuilder()
iterable.joinTo(
buffer = buffer,
separator = " - ",
prefix = "{",
postfix = "}",
limit = 3,
truncated = "(ry",
transform = { "<$it>" }
)
println(buffer)
}
{<1> - <2> - <3> - (ry}
参数 | 说明 | 格式 |
---|---|---|
separator | 分隔符 | , |
prefix | 字符串前缀 | “” |
postfix | 字符串后缀 | “” |
limit | 连接元素数量 | -1 |
truncated | 省略元素表示 | … |
transform | 各元素的格式 | null |
等价于jointTo()
使用默认Appendable
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.joinToString())
}
1, 2, 3, 4, 5
对每个元素做映射,转成新的集合
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.map { it * 10 })
}
[10, 20, 30, 40, 50]
lambda返回null时丢弃
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.mapNotNull { if (it % 2 == 0) it else null })
}
[2, 4]
获取最大、最小值,集合需要实现Comparable
接口
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.max())
println(iterable.min())
}
5
1
根据lambda计算最大、最小值
fun main(args: Array<String>) {
val iterable = listOf("zz", "yyy", "xxxx")
println(iterable.maxBy { it.length })
println(iterable.minBy { it.length })
}
xxxx
zz
通过Comparator
指定比较的方法
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.maxWith(Comparator { a, b -> b - a }))
println(iterable.minWith(Comparator { a, b -> b - a }))
}
1
5
运算符重载,集合补集
fun main(args: Array<String>) {
val iterable1 = listOf(1, 1, 2, 2, 3, 4, 5)
val iterable2 = listOf(2, 4, 5);
println(iterable1.minus(1))
println(iterable1.minus(iterable2))
println(iterable1 - iterable2)
}
[1, 2, 2, 3, 4, 5]
[1, 1, 3]
[1, 1, 3]
运算符重载,集合并集
fun main(args: Array<String>) {
val iterable1 = listOf(1, 2, 3)
val iterable2 = listOf(3, 5)
println(iterable1.plus(6))
println(iterable1.plus(iterable2))
println(iterable1 + iterable2)
}
[1, 2, 3, 6]
[1, 2, 3, 3, 5]
[1, 2, 3, 3, 5]
不包含指定条件元素时,返回true
fun main(args: Array<String>) {
val iterable1 = listOf(1, 2, 3)
val iterable2 = listOf<Int>();
println(iterable1.none())
println(iterable2.none())
println(iterable1.none {it < 2})
println(iterable1.none {it < 1})
}
false
true
false
true
按条件分割后返回Pair
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
val pair: Pair<Iterable<Int>, Iterable<Int>> = iterable.partition { it % 2 == 0 }
println(pair)
}
([2, 4], [1, 3, 5])
类似fold()
,区别是用元素的第一个元素做起始值
fun main(args: Array<String>) {
val iterable = listOf("a", "b", "c")
println(iterable.reduce {tmp, value ->
println("tmp=$tmp, value=$value")
tmp + ":" + value
})
}
tmp=a, value=b
tmp=a:b, value=c
a:b:c
确保不存在null
元素,否则异常
fun main(args: Array<String>) {
val iterable = listOf("a", "b", null, "c")
println(iterable.requireNoNulls())
}
Exception in thread "main" java.lang.IllegalArgumentException: null element found in [a, b, null, c].
at kotlin.collections.CollectionsKt___CollectionsKt.requireNoNulls(_Collections.kt:1583)
逆序
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4)
println(iterable.reversed())
}
[4, 3, 2, 1]
获取符合条件的唯一的元素
fun main(args: Array<String>) {
val iterable1 = listOf(9)
val iterable2 = listOf(1, 2, 3, 4)
println(iterable1.single())
println(iterable2.single {it == 3})
}
9
3
当两个以上符合条件时,抛出异常
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4)
println(iterable.single())
}
Exception in thread "main" java.lang.IllegalArgumentException: Collection has more than one element.
at kotlin.collections.CollectionsKt___CollectionsKt.single(_Collections.kt:487)
与single()
类似,不会抛出异常
fun main(args: Array<String>) {
val iterable1 = listOf(9)
val iterable2 = listOf(1, 2, 3, 4)
println(iterable1.singleOrNull())
println(iterable2.singleOrNull {it == 4})
println(iterable2.singleOrNull())
}
9
4
null
排序(正序、倒序)
fun main(args: Array<String>) {
val iterable = listOf(3, 1, 2, 4)
println(iterable.sorted())
println(iterable.sortedDescending())
}
[1, 2, 3, 4]
[4, 3, 2, 1]
根据lambda进行排序
fun main(args: Array<String>) {
val iterable = listOf(3, 1, 2, 4)
println(iterable.sortedBy { it * -1 })
println(iterable.sortedByDescending { it * -1 })
}
[4, 3, 2, 1]
[1, 2, 3, 4]
需要实现Comparator
接口
fun main(args: Array<String>) {
val iterable = listOf(3, 1, 2, 4)
println(iterable.sortedWith(Comparator { left, right -> right - left }))
}
[4, 3, 2, 1]
ソート方法を Comparator で実装して渡す。
使用Iterable
过滤
fun main(args: Array<String>) {
val iterable1 = listOf(1, 1, 2, 2, 3, 4, 5)
val iterable2 = listOf(2, 3, 4)
println(iterable1.subtract(iterable2))
}
[1, 5]
求和
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
println(iterable.sum())
}
6
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
println(iterable.sumBy { it * 10 })
}
60
求和返回Double型
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
println(iterable.sumByDouble { it * 1.5 })
}
9.0
截取前n个元素
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.take(3))
}
[1, 2, 3]
条件截取
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
println(iterable.takeWhile { it < 5 })
}
[1, 2, 3, 4]
向指定MutableCollection
中追加元素
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
val result: MutableCollection<Int> = mutableListOf(9)
iterable.toCollection(result)
println(result)
}
[9, 1, 2, 3]
转HashSet
fun main(args: Array<String>) {
val iterable = listOf(1, 1, 2, 2, 2, 3, 3)
val result: HashSet<Int> = iterable.toHashSet()
println(result)
}
[1, 2, 3]
转List
fun main(args: Array<String>) {
val iterable = setOf(1, 2, 3)
val list: List<Int> = iterable.toList()
println(list)
}
[1, 2, 3]
转Map
fun main(args: Array<String>) {
val iterable = listOf("foo" to "FOO", "bar" to "BAR")
val map: Map<String, String> = iterable.toMap()
println(map)
val result = mutableMapOf("fizz" to "FIZZ")
iterable.toMap(result)
println(result)
}
{foo=FOO, bar=BAR}
{fizz=FIZZ, foo=FOO, bar=BAR}
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3)
val result: MutableList<Int> = iterable.toMutableList()
println(result)
}
[1, 2, 3]
fun main(args: Array<String>) {
val iterable = listOf(1, 1, 2, 3, 3)
val result: MutableSet<Int> = iterable.toMutableSet()
println(result)
}
[1, 2, 3]
fun main(args: Array<String>) {
val iterable = listOf(1, 1, 2, 3, 3)
val result: Set<Int> = iterable.toSet()
println(result)
}
[1, 2, 3]
fun main(args: Array<String>) {
val iterable = listOf(3, 1, 2, 3, 1, 4)
val result: SortedSet<Int> = iterable.toSortedSet()
println(result)
}
[1, 2, 3, 4]
并集
fun main(args: Array<String>) {
val iterable1 = listOf(1, 2, 3, 4)
val iterable2 = listOf(2, 4, 5, 6)
val result: Set<Int> = iterable1.union(iterable2)
println(result)
}
[1, 2, 3, 4, 5, 6]
List
变 Pair
, List>
fun main(args: Array<String>) {
val iterable = listOf("one" to 1, "two" to 2, "three" to 3)
val result: Pair<List<String>, List<Int>> = iterable.unzip()
println(result)
}
([one, two, three], [1, 2, 3])
转为Iterable
fun main(args: Array<String>) {
val iterable = listOf(1, 2, 3, 4, 5)
val result: Iterable<IndexedValue<Int>> = iterable.withIndex()
result.forEach { println("index=${it.index}, value=${it.value}") }
}
index=0, value=1
index=1, value=2
index=2, value=3
index=3, value=4
index=4, value=5
两个集合,元素一一组Pair
返回List
fun main(args: Array<String>) {
val iterable1 = listOf(1, 2, 3)
val iterable2 = listOf("one", "two", "three", "four")
val result1: List<Pair<Int, String>> = iterable1.zip(iterable2)
println(result1)
val array = arrayOf(1.1, 2.2)
val result2: List<Pair<Int, Double>> = iterable1.zip(array)
println(result2)
}
[(1, one), (2, two), (3, three)]
[(1, 1.1), (2, 2.2)]
两个集合size
不等时,按照较少size
的集合zip
fun main(args: Array<String>) {
val iterable1 = listOf(1, 2, 3)
val iterable2 = listOf("one", "two", "three", "four")
val result1: List<String> = iterable1.zip(iterable2, {a, b -> "$b($a)"})
println(result1)
val array = arrayOf(1.1, 2.2)
val result2: List<Int> = iterable1.zip(array, {a, b -> (a + b*10).toInt()})
println(result2)
}
[one(1), two(2), three(3)]
[12, 24]
判断子集
fun main(args: Array<String>) {
val collection1 = listOf(1, 2, 3, 4)
val collection2 = listOf(2, 3)
val collection3 = listOf(4, 5)
println(collection1.containsAll(collection2))
println(collection1.containsAll(collection3))
}
true
false
fun main(args: Array<String>) {
val collection1 = listOf(1, 2, 3, 4)
val collection2 = listOf<Int>()
println(collection1.isEmpty())
println(collection2.isEmpty())
println(collection1.isNotEmpty())
println(collection2.isNotEmpty())
}
false
true
true
false
null
则返回空集合,否则返回自身
fun main(args: Array<String>) {
val collection1 = listOf(1, 2, 3, 4)
val collection2: Collection<Int>? = null
println(collection1.orEmpty())
println(collection2.orEmpty())
}
[1, 2, 3, 4]
[]
转成各种类型的Array,Boolean, Byte, Char, Double, Float, Int, Long, Short等
fun main(args: Array<String>) {
val collection = listOf(1, 2, 3, 4)
val array: IntArray = collection.toIntArray()
array.forEach { println(it) }
}
1
2
3
4
转Array
fun main(args: Array<String>) {
val collection = listOf(1, 2, 3, 4)
val array: Array<Int> = collection.toTypedArray()
array.forEach { println(it) }
}
1
2
3
4
逆序。与reversed()
类似,但是不改变原集合类型。
比如MutableList
仍然返回 MutableList
,而reversed()
会返回 List
fun main(args: Array<String>) {
val list = mutableListOf(1, 2, 3)
println("[before] list = $list")
val asReversed = list.asReversed()
println("[after asReversed] list = $list")
println("[after asReversed] asReversed = $asReversed")
list += 9
asReversed += 99
println("[after modify] list = $list")
println("[after modify] asReversed = $asReversed")
}
[before] list = [1, 2, 3]
[after asReversed] list = [1, 2, 3]
[after asReversed] asReversed = [3, 2, 1]
[after modify] list = [99, 1, 2, 3, 9]
[after modify] asReversed = [9, 3, 2, 1, 99]
二分查找,fromIndex
、toIndex
指定查找范围
fun main(args: Array<String>) {
val list = listOf(1, 2, 2, 3, 3, 3)
println(list.binarySearch(3))
println(list.binarySearch(9))
println(list.binarySearch(element = 3, fromIndex = 0, toIndex = 2))
println(list.binarySearch(element = 3, comparator = Comparator { a, b -> a - b }))
}
4
-7
-3
4
将元素转成selector
,然后与第一个参数比较,返回命中的结果index
fun main(args: Array<String>) {
val list = listOf("I", "he", "her", "you")
println(list.binarySearchBy("Thank you", selector = { "Thank $it" }))
}
3
结构后的元素。没啥意义
fun main(args: Array<String>) {
val list = listOf("one", "two", "three", "four", "five")
println(list.component1())
println(list.component2())
println(list.component3())
println(list.component4())
println(list.component5())
}
one
two
three
four
five
从尾部删除
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
println(list.dropLast(2))
}
[1, 2, 3]
从尾部开始根据lambda删除
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
println(list.dropLastWhile { it > 2 })
}
[1, 2]
从尾部开始执行fold()
fun main(args: Array<String>) {
val list = listOf("a", "b", "c")
println(list.foldRight("Z", { value, buf -> buf + value }))
}
Zcba
获取指定值或默认值
fun main(args: Array<String>) {
val list = listOf(1, 2, 3)
println(list.getOrElse(0, { 9 }))
println(list.getOrElse(4, { 9 }))
}
1
9
指定值或null
fun main(args: Array<String>) {
val list = listOf(1, 2, 3)
println(list.getOrNull(0))
println(list.getOrNull(4))
}
1
null
尾部开始reduce()
fun main(args: Array<String>) {
val list = listOf("a", "b", "c")
println(list.reduceRight { value, tmp ->
println("value=$value, tmp=$tmp")
tmp + ":" + value
})
}
value=b, tmp=c
value=a, tmp=c:b
c:b:a
切片
fun main(args: Array<String>) {
val list = listOf("0:one", "1:two", "2:three", "3:four", "4:five")
println(list.slice(2..4))
val indices = listOf(1, 3, 4)
println(list.slice(indices))
}
[2:three, 3:four, 4:five]
[1:two, 3:four, 4:five]
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
println(list.takeLast(2))
}
[4, 5]
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5)
println(list.takeLastWhile { it > 2 })
}
[3, 4, 5]
fun main(args: Array<String>) {
val mutableIterable = mutableListOf(1, 2, 3, 1, 2, 3)
mutableIterable.removeAll { it == 3 }
println(mutableIterable)
}
[1, 2, 1, 2]
保留
fun main(args: Array<String>) {
val mutableIterable = mutableListOf(1, 2, 3, 1, 2, 3)
mutableIterable.retainAll { it == 3 }
println(mutableIterable)
}
[3, 3]
fun main(args: Array<String>) {
val mutableCollection = mutableListOf(1, 2, 3)
val iterable = listOf(7, 8, 9)
mutableCollection.addAll(iterable)
println(mutableCollection)
}
[1, 2, 3, 7, 8, 9]
操作符重载 -=
fun main(args: Array<String>) {
val mutableCollection = mutableListOf(1, 2, 3, 4, 5)
val iterable = listOf(2, 4)
mutableCollection.minusAssign(iterable)
println(mutableCollection)
mutableCollection -= 5
println(mutableCollection)
}
[1, 3, 5]
[1, 3]
操作符重载 +=
fun main(args: Array<String>) {
val mutableCollection = mutableListOf(1, 2, 3)
val iterable = listOf(7, 8)
mutableCollection.plusAssign(iterable)
println(mutableCollection)
mutableCollection += 9
println(mutableCollection)
}
[1, 2, 3, 7, 8]
[1, 2, 3, 7, 8, 9]
fun main(args: Array<String>) {
val mutableCollection = mutableListOf(1, 2, 3)
mutableCollection.remove(2)
println(mutableCollection)
}
[1, 3]
逆序
fun main(args: Array<String>) {
val mutableList = mutableListOf(1, 2, 3)
mutableList.reverse()
println(mutableList)
}
[3, 2, 1]
fun main(args: Array<String>) {
val mutableList = mutableListOf(3, 1, 2)
mutableList.sort()
println(mutableList)
mutableList.sortDescending()
println(mutableList)
}
[1, 2, 3]
[3, 2, 1]
fun main(args: Array<String>) {
val mutableList = mutableListOf("aaa", "bb", "c")
mutableList.sortBy { it.length }
println(mutableList)
mutableList.sortByDescending { it.length }
println(mutableList)
}
[c, bb, aaa]
[aaa, bb, c]
fun main(args: Array<String>) {
val mutableList = mutableListOf(2, 3, 1)
mutableList.sortWith(Comparator { a, b -> b - a})
println(mutableList)
}
[3, 2, 1]
所有Entry
满足条件
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.all { it.key is String })
println(map.all { it.key.contains("o") })
}
true
false
任意Entry
满足条件
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.any { it.key.contains("o") })
println(map.any { it.key.isEmpty() })
}
true
false
判断是否包含指定key, 等同containsKey()
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.contains("one"))
println(map.contains("ONE"))
}
true
false
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.containsKey("one"))
println(map.containsKey("ONE"))
}
true
false
是否包含指定value
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.containsValue("one"))
println(map.containsValue("ONE"))
}
false
true
符合条件的数量
fun main(args: Array) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.count())
println(map.count { it.key.contains("t") })
}
3
2
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.filter { it.key.contains("t") })
println(map.filterNot { it.key.contains("t") })
}
{two=TWO, three=THREE}
{one=ONE}
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.filterKeys { key -> key.contains("o") })
println(map.filterValues { value -> value.contains("T") })
}
{one=ONE, two=TWO}
{two=TWO, three=THREE}
按照lambda打平返回List
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.flatMap { listOf(it.key, it.value) })
}
[one, ONE, two, TWO, three, THREE]
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
map.forEach { println("key=${it.key}, value=${it.value}") }
}
key=one, value=ONE
key=two, value=TWO
key=three, value=THREE
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.getOrElse("one", {"DEFAULT"}))
println(map.getOrElse("nine", {"DEFAULT"}))
}
ONE
DEFAULT
fun main(args: Array<String>) {
val map = mapOf<String, String>()
println(map.isEmpty())
println(map.isNotEmpty())
}
true
false
fun main(args: Array<String>) {
val map1 = mapOf("one" to "ONE")
val map2 = mapOf<String, String>()
println(map1.none())
println(map2.none())
println(map1.none {it.key == "two"})
}
false
true
true
fun main(args: Array<String>) {
val map1 = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
val map2: Map<String, String>? = null
println(map1.orEmpty())
println(map2.orEmpty())
}
{one=ONE, two=TWO, three=THREE}
{}
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.map { if (it.key == "two") null else "${it.key}=${it.value}" })
println(map.mapNotNull { if (it.key == "two") null else "${it.key}=${it.value}" })
}
[one=ONE, null, three=THREE]
[one=ONE, three=THREE]
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.mapKeys { "<${it.key}>" })
println(map.mapValues { "<${it.value}>" })
}
{=ONE, =TWO, =THREE}
{one=, two=, three=}
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.maxBy { it.key })
println(map.minBy { it.key })
}
two=TWO
one=ONE
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
val comparator = Comparator<Map.Entry<String, String>> { a, b -> a.key.compareTo(b.key) }
println(map.maxWith(comparator))
println(map.minWith(comparator))
}
two=TWO
one=ONE
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(map.plus(mapOf("four" to "FOUR")))
println(map.plus("five" to "FIVE"))
println(map.plus(listOf("six" to "SIX")))
println(map + ("seven" to "SEVEN"))
}
{one=ONE, two=TWO, three=THREE, four=FOUR}
{one=ONE, two=TWO, three=THREE, five=FIVE}
{one=ONE, two=TWO, three=THREE, six=SIX}
{one=ONE, two=TWO, three=THREE, seven=SEVEN}
Map
转 List
fun main(args: Array<String>) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
val list: List<Pair<String, String>> = map.toList()
println(list)
}
[(one, ONE), (two, TWO), (three, THREE)]
转成java.util.Properties
fun main(args: Array) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
val properties: Properties = map.toProperties()
println(properties)
}
{two=TWO, one=ONE, three=THREE}
转成java.util.SortedMap
fun main(args: Array) {
val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
val sortedMap: SortedMap = map.toSortedMap()
println(sortedMap)
}
{one=ONE, three=THREE, two=TWO}
获取指定值不存在时创建默认值,并将默认值插入Map
fun main(args: Array<String>) {
val mutableMap = mutableMapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
println(mutableMap.getOrPut("one", {"DEFAULT"}))
println(mutableMap)
println(mutableMap.getOrPut("four", {"DEFAULT"}))
println(mutableMap)
}
ONE
{one=ONE, two=TWO, three=THREE}
DEFAULT
{one=ONE, two=TWO, three=THREE, four=DEFAULT}
fun main(args: Array<String>) {
val mutableMap = mutableMapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
mutableMap.putAll(mapOf("four" to "FOUR", "five" to "FIVE"))
println(mutableMap)
mutableMap.putAll(listOf("six" to "SIX"))
println(mutableMap)
}
{one=ONE, two=TWO, three=THREE, four=FOUR, five=FIVE}
{one=ONE, two=TWO, three=THREE, four=FOUR, five=FIVE, six=SIX}
+=
的运算符重载,同putAll()
fun main(args: Array<String>) {
val mutableMap = mutableMapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")
mutableMap.plusAssign(mapOf("four" to "FOUR"))
mutableMap.plusAssign("five" to "FIVE")
mutableMap.plusAssign(listOf("six" to "SIX"))
mutableMap += "seven" to "SEVEN"
println(mutableMap)
}
{one=ONE, two=TWO, three=THREE, four=FOUR, five=FIVE, six=SIX, seven=SEVEN}