Kotlin|Kotlin集合操作符整理汇总Iterable/Collection/List/Set/Map

Kotlin|Kotlin集合操作符整理汇总Iterable/Collection/List/Set/Map
文章图片

Kotlin的集合类虽然继承自Java,但是增加了更多能力,使用更具优势

  • 分为immutablemutable两类,默认的immutable类型使用起来更安全
  • 提供更多工厂方法创建对象,例如listOfsetOf
  • 提供了很多类似于StreamAPI的操作符(本质是扩展函数),例如filter()

接口体系 ListSetMap等常用集合类的继承体系与JDK基本一样,只是接口类型默认是immutable的,没有定义用于改变集合对象的“写”方法。可写的集合类需要通过另一套MutableXXX接口实现
Kotlin|Kotlin集合操作符整理汇总Iterable/Collection/List/Set/Map
文章图片

Java的兼容 Kotlin中调用Java代码时,集合类会自动转换,
例如 java.util.Iterator转换为kotlin.collection.Iterator
因此,即使Java集合类对象也可以使用Kotlin集合操作符进行操作


创建集合 Kotlin鼓励使用工厂模式创建集合,提供了多种工厂放阿飞
immutable集合
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>) { 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]

mutable集合
val list = mutableListOf(1, 2, 3) val map = mutableMapOf("foo" to "FOO", "bar" to "BAR") val set = mutableSetOf(9, 8, 7)

Java结合类 对Java的各集合类型也提供了工厂方法,但因为创建的对象都是mutable的,所以并不推荐使用。
fun main(args: Array>) { printClass("arrayListOf", arrayListOf())printClass("hashSetOf", hashSetOf()) printClass("linkedSetOf", linkedSetOf()) printClass("sortedSetOf", sortedSetOf())printClass("hashMapOf", hashMapOf()) printClass("linkedMapOf", linkedMapOf()) printClass("sortedMapOf", sortedMapOf()) }fun printClass(functionName: String, collection: Any) { println("$functionName = ${collection.javaClass}") }

# 结果 arrayListOf = class java.util.ArrayListhashSetOf = class java.util.HashSet linkedSetOf = class java.util.LinkedHashSet sortedSetOf = class java.util.TreeSethashMapOf = class java.util.HashMap linkedMapOf = class java.util.LinkedHashMap sortedMapOf = class java.util.TreeMap

属性 indices indicesindex的复数形式。
顾名思义,其存储着Array或Collection中index的IntRange
fun main(args: Array>) { 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

lastIndex 最后一个元素的index,相当于size-1
fun main(args: Array>) { 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分别介绍各操作符的使用:
Iterable all() 所有元素均命中判断条件,返回true
fun main(args: Array>) { val iterable = listOf(1, 2, 3)println(iterable.all { it < 4 }) println(iterable.all { it < 3 }) }

true false

any() 任意元素命中判断条件,返回true
fun main(args: Array>) { val iterable = listOf(1, 2, 3)println(iterable.any { it < 4 }) println(iterable.any { it < 0 }) }

true false

associate() 集合转为map,元素为key
fun main(args: Array>) { val iterable = listOf(1, 2, 3)val map = iterable.associate { it to it*10 }println(map) }

{1=10, 2=20, 3=30}

associateBy() 集合转为Map,元素为value
fun main(args: Array>) { val iterable = listOf(1, 2, 3)val map = iterable.associateBy { it*10 }println(map) }

{10=1, 20=2, 30=3}

average() 元素平均值。元素类型必须为IntegerFloat等数字类型
fun main(args: Array>) { val iterable = listOf(1, 2, 3)val average = iterable.average()println(average) }

2.0

contains() 判断是否含有指定元素
fun main(args: Array>) { val iterable = listOf(1, 2, 3)println(iterable.contains(2)) println(iterable.contains(4)) }

true false

count() 元素个数 or 满足lambda条件的元素个数
fun main(args: Array>) { val iterable = listOf(1, 2, 3)println(iterable.count()) println(iterable.count {it % 2 == 1}) }

3 2

distinct() 去重
fun main(args: Array>) { val iterable = listOf(1, 2, 1, 2, 2, 3, 1, 3)println(iterable.distinct()) }

[1, 2, 3]

distinctBy() 根据lambda去重
fun main(args: Array>) { val iterable = listOf("foo", "bar", "fizz", "buzz", "hoge")println(iterable.distinctBy { it.length }) }

[foo, fizz]

drop() 丢弃某元素
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.drop(2)) }

[3, 4, 5]

dropWhile() 根据lambda丢弃元素
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.dropWhile { it != 4 }) }

[4, 5]

elementAt() 获取指定元素,参数非法时会IndexOutOfBoundsException
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.elementAt(2)) }

3

elementAtOrElse() 获取指定元素,参数非法时返回lambda的结果
fun main(args: Array>) { val iterable = listOf(1, 2, 3)println(iterable.elementAtOrElse(0, { it * 10 })) println(iterable.elementAtOrElse(5, { it * 10 })) }

1 50

elementAtOrNull() 获取指定元素,参数非法时返回null
fun main(args: Array>) { val iterable = listOf(1, 2, 3)println(iterable.elementAtOrNull(0)) println(iterable.elementAtOrNull(5)) }

1 null

filter() lambda条件过滤
fun main(args: Array>) { val iterable = listOf(1, 2, 3)println(iterable.filter { it % 2 != 0 }) }

[1, 3]

filterIsInstance() 过滤指定类型的元素
fun main(args: Array>) { val iterable: Iterable<*> = listOf(1, "foo", 2.4, false)println(iterable.filterIsInstance()) println(iterable.filterIsInstance(String::class.java)) }

[1, 2.4]

filterNot() 抛弃符合条件的元素
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.filterNot { it % 2 == 0 }) }

[1, 3, 5]

filterNotNull() 过滤非空元素
fun main(args: Array>) { val iterable = listOf(1, null, 3, null, 5)println(iterable.filterNotNull()) }

[1, 3, 5]

find() 第一个符合条件的元素,等价于 firstOrNull()
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.find { it % 2 == 0 }) println(iterable.find { it % 6 == 0 }) }

2 null

findLast() 从后往前第一个符合条件的元素,等价于lastOrNull()
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.findLast { it % 2 == 0 }) println(iterable.findLast { it % 6 == 0 }) }

4 null

first() 第一个符合条件的元素,找不到返回异常
fun main(args: Array>) { 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.

firstOrNull()
fun main(args: Array>) { 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

last()
fun main(args: Array>) { 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.

lastOrNull()
fun main(args: Array>) { 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

flatMap() 连接多个Iterable
fun main(args: Array>) { val iterable: Iterable> = 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]

flatten() 拍平子Iterable
fun main(args: Array>) { val iterable: Iterable> = 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]

fold() 对每个元素逐个执行lambda运算,运算结果作为下次运算的输入。
第一个参数为启动输入
fun main(args: Array>) { val iterable = listOf("a", "b", "c")println(iterable.fold("Z", { buf, value -> buf + value })) }

Zabc

forEach() 循环遍历
fun main(args: Array>) { val iterable = listOf(1, 2, 3)iterable.forEach { println(it) } }

1 2 3

groupBy() 根据条件分组
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5, 6, 7)val result1: Map, List> = iterable.groupBy { if (it % 2 == 0) "偶数" else "奇数" }println(result1)val result2: Map, List>> = iterable.groupBy( { if (it % 2 == 0) "偶数" else "奇数" }, { "<$it>"} )println(result2) }

{奇数=[1, 3, 5, 7], 偶数=[2, 4, 6]} {奇数=[<1>, <3>, <5>, <7>], 偶数=[<2>, <4>, <6>]}

indexOfFirst()
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.indexOfFirst { it % 2 == 0 }) }

1

indextOfLast()
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.indexOfLast { it % 2 == 0 }) }

3

intersect() 去重后返回Set
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5) val other = listOf(2, 3, 5, 2)val result: Set = iterable.intersect(other)println(result) }

[2, 3, 5]

joinTo() 将集合以字符串输出,可以通过Appendable指定元素的连接格式,默认是半角逗号
fun main(args: Array>) { 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>) { 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
joinToString() 等价于jointTo()使用默认Appendable
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.joinToString()) }

1, 2, 3, 4, 5

map() 对每个元素做映射,转成新的集合
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.map { it * 10 }) }

[10, 20, 30, 40, 50]

mapNotNull() lambda返回null时丢弃
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.mapNotNull { if (it % 2 == 0) it else null }) }

[2, 4]

max(), min() 获取最大、最小值,集合需要实现Comparable接口
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.max()) println(iterable.min()) }

5 1

maxBy(), minBy() 根据lambda计算最大、最小值
fun main(args: Array>) { val iterable = listOf("zz", "yyy", "xxxx")println(iterable.maxBy { it.length }) println(iterable.minBy { it.length }) }

xxxx zz

maxWith(), minWith() 通过Comparator指定比较的方法
fun main(args: Array>) { 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

minus() 运算符重载,集合补集
fun main(args: Array>) { 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]

plus() 运算符重载,集合并集
fun main(args: Array>) { 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]

none() 不包含指定条件元素时,返回true
fun main(args: Array>) { val iterable1 = listOf(1, 2, 3) val iterable2 = listOf(); println(iterable1.none()) println(iterable2.none())println(iterable1.none {it < 2}) println(iterable1.none {it < 1}) }

false true false true

partition() 按条件分割后返回Pair
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)val pair: Pair, Iterable> = iterable.partition { it % 2 == 0 }println(pair) }

([2, 4], [1, 3, 5])

reduce() 类似fold(),区别是用元素的第一个元素做起始值
fun main(args: Array>) { val iterable = listOf("a", "b", "c")println(iterable.reduce {tmp, value -> println("tmp=$tmp, value=https://www.it610.com/article/$value") tmp + ":" + value }) }

tmp=a, value=https://www.it610.com/article/b tmp=a:b, value=c a:b:c

requireNoNulls() 确保不存在null元素,否则异常
fun main(args: Array>) { 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)

reversed() 逆序
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4)println(iterable.reversed()) }

[4, 3, 2, 1]

single() 获取符合条件的唯一的元素
fun main(args: Array>) { 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>) { val iterable = listOf(1, 2, 3, 4)println(iterable.single())

【Kotlin|Kotlin集合操作符整理汇总Iterable/Collection/List/Set/Map】}
Exception in thread "main" java.lang.IllegalArgumentException: Collection has more than one element. at kotlin.collections.CollectionsKt___CollectionsKt.single(_Collections.kt:487)

singleOrNull() 与single()类似,不会抛出异常
fun main(args: Array>) { 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

sorted(), sortedDescending() 排序(正序、倒序)
fun main(args: Array>) { val iterable = listOf(3, 1, 2, 4)println(iterable.sorted()) println(iterable.sortedDescending()) }

[1, 2, 3, 4] [4, 3, 2, 1]

sortedBy(), sortedByDescending() 根据lambda进行排序
fun main(args: Array>) { 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]

sortedWith() 需要实现Comparator接口
fun main(args: Array>) { val iterable = listOf(3, 1, 2, 4)println(iterable.sortedWith(Comparator { left, right -> right - left })) }

[4, 3, 2, 1]

ソート方法を Comparator で実装して渡す。
subtract() 使用Iterable过滤
fun main(args: Array>) { val iterable1 = listOf(1, 1, 2, 2, 3, 4, 5) val iterable2 = listOf(2, 3, 4)println(iterable1.subtract(iterable2)) }

[1, 5]

sum() 求和
fun main(args: Array>) { val iterable = listOf(1, 2, 3)println(iterable.sum()) }

6

sumBy()
fun main(args: Array>) { val iterable = listOf(1, 2, 3)println(iterable.sumBy { it * 10 }) }

60

sumByDouble() 求和返回Double型
fun main(args: Array>) { val iterable = listOf(1, 2, 3)println(iterable.sumByDouble { it * 1.5 }) }

9.0

take() 截取前n个元素
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.take(3)) }

[1, 2, 3]

takeWhile() 条件截取
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)println(iterable.takeWhile { it < 5 })

}
[1, 2, 3, 4]

toCollection() 向指定MutableCollection中追加元素
fun main(args: Array>) { val iterable = listOf(1, 2, 3)val result: MutableCollection = mutableListOf(9)iterable.toCollection(result)println(result) }

[9, 1, 2, 3]

toHashSet() 转HashSet
fun main(args: Array>) { val iterable = listOf(1, 1, 2, 2, 2, 3, 3)val result: HashSet = iterable.toHashSet()println(result) }

[1, 2, 3]

toList() 转List
fun main(args: Array>) { val iterable = setOf(1, 2, 3)val list: List = iterable.toList()println(list) }

[1, 2, 3]

toMap() 转Map
fun main(args: Array>) { val iterable = listOf("foo" to "FOO", "bar" to "BAR")val map: Map, 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}

toMutableList()
fun main(args: Array>) { val iterable = listOf(1, 2, 3)val result: MutableList = iterable.toMutableList()println(result) }

[1, 2, 3]

toMutableSet()
fun main(args: Array>) { val iterable = listOf(1, 1, 2, 3, 3)val result: MutableSet = iterable.toMutableSet()println(result) }

[1, 2, 3]

toSet()
fun main(args: Array>) { val iterable = listOf(1, 1, 2, 3, 3)val result: Set = iterable.toSet()println(result) }

[1, 2, 3]

toSortedSet()
fun main(args: Array>) { val iterable = listOf(3, 1, 2, 3, 1, 4)val result: SortedSet = iterable.toSortedSet()println(result) }

[1, 2, 3, 4]

union() 并集
fun main(args: Array>) { val iterable1 = listOf(1, 2, 3, 4) val iterable2 = listOf(2, 4, 5, 6)val result: Set = iterable1.union(iterable2)println(result) }

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

unzip() List>Pair, List>
fun main(args: Array>) { val iterable = listOf("one" to 1, "two" to 2, "three" to 3)val result: Pair, List> = iterable.unzip()println(result) }

([one, two, three], [1, 2, 3])

withIndex() 转为Iterable>
fun main(args: Array>) { val iterable = listOf(1, 2, 3, 4, 5)val result: Iterable> = iterable.withIndex()result.forEach { println("index=${it.index}, value=https://www.it610.com/article/${it.value}") } }

index=0, value=https://www.it610.com/article/1 index=1, value=2 index=2, value=3 index=3, value=4 index=4, value=5

zip() 两个集合,元素一一组Pair返回List
fun main(args: Array>) { val iterable1 = listOf(1, 2, 3)val iterable2 = listOf("one", "two", "three", "four") val result1: List> = iterable1.zip(iterable2) println(result1)val array = arrayOf(1.1, 2.2) val result2: List> = iterable1.zip(array) println(result2) }

[(1, one), (2, two), (3, three)] [(1, 1.1), (2, 2.2)]

两个集合size不等时,按照较少size的集合zip
fun main(args: Array>) { val iterable1 = listOf(1, 2, 3)val iterable2 = listOf("one", "two", "three", "four") val result1: List> = iterable1.zip(iterable2, {a, b -> "$b($a)"}) println(result1)val array = arrayOf(1.1, 2.2) val result2: List = iterable1.zip(array, {a, b -> (a + b*10).toInt()}) println(result2) }

[one(1), two(2), three(3)] [12, 24]

containsAll() 判断子集
fun main(args: Array>) { 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


Collection isEmpty(), isNotEmpty()
fun main(args: Array>) { val collection1 = listOf(1, 2, 3, 4) val collection2 = listOf()println(collection1.isEmpty()) println(collection2.isEmpty())println(collection1.isNotEmpty()) println(collection2.isNotEmpty()) }

false true true false

orEmpty() null则返回空集合,否则返回自身
fun main(args: Array>) { val collection1 = listOf(1, 2, 3, 4) val collection2: Collection? = nullprintln(collection1.orEmpty()) println(collection2.orEmpty()) }

[1, 2, 3, 4] []

to***Array() 转成各种类型的Array,Boolean, Byte, Char, Double, Float, Int, Long, Short等
fun main(args: Array>) { val collection = listOf(1, 2, 3, 4)val array: IntArray = collection.toIntArray()array.forEach { println(it) } }

1 2 3 4

toTypedArray() 转Array
fun main(args: Array>) { val collection = listOf(1, 2, 3, 4)val array: Array = collection.toTypedArray()array.forEach { println(it) } }

1 2 3 4


List asReversed() 逆序。与reversed() 类似,但是不改变原集合类型。
比如MutableList仍然返回 MutableList,而reversed() 会返回 List
fun main(args: Array>) { 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 += 99println("[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]

binarySearch() 二分查找,fromIndextoIndex指定查找范围
fun main(args: Array>) { 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

binarySearchBy() 将元素转成selector,然后与第一个参数比较,返回命中的结果index
fun main(args: Array>) { val list = listOf("I", "he", "her", "you")println(list.binarySearchBy("Thank you", selector = { "Thank $it" })) }

3

component*() 结构后的元素。没啥意义
fun main(args: Array>) { 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

dropLast() 从尾部删除
fun main(args: Array>) { val list = listOf(1, 2, 3, 4, 5)println(list.dropLast(2)) }

[1, 2, 3]

dropLastWhile() 从尾部开始根据lambda删除
fun main(args: Array>) { val list = listOf(1, 2, 3, 4, 5)println(list.dropLastWhile { it > 2 }) }

[1, 2]

foldRight() 从尾部开始执行fold()
fun main(args: Array>) { val list = listOf("a", "b", "c")println(list.foldRight("Z", { value, buf -> buf + value })) }

Zcba

getOrElse() 获取指定值或默认值
fun main(args: Array>) { val list = listOf(1, 2, 3)println(list.getOrElse(0, { 9 })) println(list.getOrElse(4, { 9 })) }

1 9

getOrNull() 指定值或null
fun main(args: Array>) { val list = listOf(1, 2, 3)println(list.getOrNull(0)) println(list.getOrNull(4)) }

1 null

reduceRight() 尾部开始reduce()
fun main(args: Array>) { val list = listOf("a", "b", "c")println(list.reduceRight { value, tmp -> println("value=https://www.it610.com/article/$value, tmp=$tmp") tmp + ":" + value }) }

value=https://www.it610.com/article/b, tmp=c value=a, tmp=c:b c:b:a

slice() 切片
fun main(args: Array>) { 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]

takeLast()
fun main(args: Array>) { val list = listOf(1, 2, 3, 4, 5)println(list.takeLast(2)) }

[4, 5]

takeLastWhile()
fun main(args: Array>) { val list = listOf(1, 2, 3, 4, 5)println(list.takeLastWhile { it > 2 }) }

[3, 4, 5]


MutableIterable removeAll()
fun main(args: Array>) { val mutableIterable = mutableListOf(1, 2, 3, 1, 2, 3)mutableIterable.removeAll { it == 3 }println(mutableIterable) }

[1, 2, 1, 2]

retainAll() 保留
fun main(args: Array>) { val mutableIterable = mutableListOf(1, 2, 3, 1, 2, 3)mutableIterable.retainAll { it == 3 }println(mutableIterable) }

[3, 3]

MutableCollection addAll()
fun main(args: Array>) { val mutableCollection = mutableListOf(1, 2, 3) val iterable = listOf(7, 8, 9)mutableCollection.addAll(iterable)println(mutableCollection) }

[1, 2, 3, 7, 8, 9]

minusAssign() 操作符重载 -=
fun main(args: Array>) { 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]

plusAssign() 操作符重载 +=
fun main(args: Array>) { 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]

remove()
fun main(args: Array>) { val mutableCollection = mutableListOf(1, 2, 3)mutableCollection.remove(2)println(mutableCollection) }

[1, 3]


MutableList reverse() 逆序
fun main(args: Array>) { val mutableList = mutableListOf(1, 2, 3)mutableList.reverse()println(mutableList) }

[3, 2, 1]

sort(), sortDescending()
fun main(args: Array>) { val mutableList = mutableListOf(3, 1, 2)mutableList.sort() println(mutableList)mutableList.sortDescending() println(mutableList) }

[1, 2, 3] [3, 2, 1]

sortBy(), sortByDescending()
fun main(args: Array>) { val mutableList = mutableListOf("aaa", "bb", "c")mutableList.sortBy { it.length } println(mutableList)mutableList.sortByDescending { it.length } println(mutableList) }

[c, bb, aaa] [aaa, bb, c]

sortWith()
fun main(args: Array>) { val mutableList = mutableListOf(2, 3, 1)mutableList.sortWith(Comparator { a, b ->b - a}) println(mutableList) }

[3, 2, 1]


Map 所有Entry满足条件
all()
fun main(args: Array>) { 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

any() 任意Entry满足条件
fun main(args: Array>) { 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

contains() 判断是否包含指定key, 等同containsKey()
fun main(args: Array>) { val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")println(map.contains("one")) println(map.contains("ONE")) }

true false

containsKey()
fun main(args: Array>) { val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")println(map.containsKey("one")) println(map.containsKey("ONE")) }

true false

containsValue() 是否包含指定value
fun main(args: Array>) { val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")println(map.containsValue("one")) println(map.containsValue("ONE")) }

false true

count() 符合条件的数量
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

filter(), filterNot()
fun main(args: Array>) { 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}

filterKeys(), filterValues()
fun main(args: Array>) { 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}

flatMap() 按照lambda打平返回List
fun main(args: Array>) { 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]

forEach()
fun main(args: Array>) { val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")map.forEach { println("key=${it.key}, value=https://www.it610.com/article/${it.value}") } }

key=one, value=https://www.it610.com/article/ONE key=two, value=TWO key=three, value=THREE

getOrElse()
fun main(args: Array>) { val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")println(map.getOrElse("one", {"DEFAULT"})) println(map.getOrElse("nine", {"DEFAULT"})) }

ONE DEFAULT

isEmpty(), isNotEmpty()
fun main(args: Array>) { val map = mapOf, String>()println(map.isEmpty()) println(map.isNotEmpty()) }

true false

none()
fun main(args: Array>) { val map1 = mapOf("one" to "ONE") val map2 = mapOf, String>()println(map1.none()) println(map2.none())println(map1.none {it.key == "two"}) }

false true true

orEmpty()
fun main(args: Array>) { val map1 = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE") val map2: Map, String>? = nullprintln(map1.orEmpty()) println(map2.orEmpty()) }

{one=ONE, two=TWO, three=THREE} {}

map(), mapNotNull()
fun main(args: Array>) { 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]

mapKeys(), mapValues()
fun main(args: Array>) { 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=}

maxBy(), minBy()
fun main(args: Array>) { 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

maxWith(), minWith()
fun main(args: Array>) { val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE")val comparator = Comparator> { a, b -> a.key.compareTo(b.key) }println(map.maxWith(comparator)) println(map.minWith(comparator)) }

two=TWO one=ONE

plus()
fun main(args: Array>) { 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}

toList() MapList>
fun main(args: Array>) { val map = mapOf("one" to "ONE", "two" to "TWO", "three" to "THREE") val list: List> = map.toList()println(list) }

[(one, ONE), (two, TWO), (three, THREE)]

toProperties() 转成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}

toSortedMap() 转成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}


MutableMap getOrPut 获取指定值不存在时创建默认值,并将默认值插入Map
fun main(args: Array>) { 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}

putAll
fun main(args: Array>) { 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}

plusAssign +=的运算符重载,同putAll()
fun main(args: Array>) { 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}

    推荐阅读