Kotlin 集合List SetMap操作汇总
Posted 黄毛火烧雪下
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Kotlin 集合List SetMap操作汇总相关的知识,希望对你有一定的参考价值。
一、list 转成已逗号等分割的String
val numbers = listOf("one", "two", "three", "four")
println(numbers.joinToString(separator = " | ", prefix = "start: ", postfix = ": end"))
start: one | two | three | four: end
二、划分
val numbers = listOf("one","two","three","four")
val (match,rest)=numbers.partition it.length>3
println(match)
println(rest)
[three, four]
[one, two]
三、 加减操作符
var numbers = listOf(Person("张三",12), Person("李四",10))
val plusList = numbers + Person("王五",12)
numbers +=Person("王五",12)
val minusList = numbers - Person("张三",12)
println(plusList)
println(numbers)
println(minusList)
[Person(name=张三, age=12), Person(name=李四, age=10), Person(name=王五, age=12)]
[Person(name=张三, age=12), Person(name=李四, age=10), Person(name=王五, age=12)]
[Person(name=李四, age=10), Person(name=王五, age=12)]
四、分组
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.groupBy it.first().uppercase() )
println(numbers.groupBy(keySelector = it.first(), valueTransform = it.uppercase()))
println(numbers.groupingBy it.first() .eachCount())
O=[one], T=[two, three], F=[four, five]
o=[ONE], t=[TWO, THREE], f=[FOUR, FIVE]
o=1, t=2, f=2
五、取集合的一部分
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分块
val numbers = (0..13).toList()
println(numbers.chunked(3))
println(numbers.chunked(3) it.sum() )
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13]]
[3, 12, 21, 30, 25]
七、按条件取单个元素
val numbers = listOf("one", "two", "three", "four", "five", "six")
//会发生异常
println(numbers.first it.length > 6 )
//意见使用这个
println(numbers.firstOrNull it.length > 6 )
Exception in thread "main" java.util.NoSuchElementException: Collection contains no element matching the predicate.
八、随机取元素
val numbers = listOf(1, 2, 3, 4)
println(numbers.random())
九、 检测元素存在与否 contains() 和 in
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.contains("four"))
println("zero" in numbers)
println(numbers.containsAll(listOf("four", "two")))
println(numbers.containsAll(listOf("one", "zero")))
true
false
true
false
十、isEmpty() 和 isNotEmpty()
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.isEmpty())
println(numbers.isNotEmpty())
val empty = emptyList<String>()
println(empty.isEmpty())
println(empty.isNotEmpty())
false
true
true
false
十一、排序
fun main(args: Array<String>)
val lengthComparator = Comparator str1: String, str2: String -> str1.length - str2.length
println(listOf("aaa", "bb", "c").sortedWith(lengthComparator))
println(Version(1, 2) > Version(1, 3))
println(Version(2, 0) > Version(1, 5))
println(listOf("aaa", "bb", "c").sortedWith(compareBy it.length ))
class Version(val major: Int, val minor: Int) : Comparable<Version>
override fun compareTo(other: Version): Int = when
this.major != other.major -> this.major compareTo other.major
this.minor != other.minor -> this.minor compareTo other.minor
else -> 0
[c, bb, aaa]
false
true
[c, bb, aaa]
十二、聚合操作
val numbers = listOf(5, 2, 10, 4)
println("Count: $numbers.count()")
println("Max: $numbers.maxOrNull()")
println("Min: $numbers.minOrNull()")
println("Average: $numbers.average()")
println("Sum: $numbers.sum()")
val simpleSum = numbers.reduce sum, element -> sum + element
println(simpleSum)
val sumDoubled = numbers.fold(0) sum, element -> sum + element * 2
println(sumDoubled)
Count: 4
Max: 10
Min: 2
Average: 5.25
Sum: 21
21
4
十三、删除元素
val numbers = mutableListOf(1, 2, 3, 4, 3)
numbers.remove(3) // 删除了第一个 `3`
println(numbers)
numbers.remove(5) // 什么都没删除
println(numbers)
[1, 2, 4, 3]
[1, 2, 4, 3]
十四、按索引取元素
val numbers = listOf(1, 2, 3, 4)
println(numbers.get(0))
println(numbers[0])
//numbers.get(5) // exception!
println(numbers.getOrNull(5)) // null
println(numbers.getOrElse(5, it)) // 5
1
1
null
5
十五、Comparator 二分搜索 排序
fun main(args: Array<String>)
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sort()
println(numbers)
println(numbers.binarySearch("two")) // 3
println(numbers.binarySearch("z")) // -5
println(numbers.binarySearch("two", 0, 2)) // -3
val productList = listOf(
Person("WebStorm", 49),
Person("AppCode", 49),
Person("DotTrace", 129),
Person("ReSharper", 14)
)
println(
productList.binarySearch(
Person("AppCode", 99),
compareBy<Person> it.age .thenBy it.name )
)
println( productList.sortedWith(compareBy<Person> it.age .thenBy it.name ))
data class Person(var name: String, var age: Int)
[four, one, three, two]
3
-5
-3
1
[Person(name=ReSharper, age=14), Person(name=AppCode, age=49), Person(name=WebStorm, age=49), Person(name=DotTrace, age=129)]
十六、Set 交集
val numbers = setOf("one", "two", "three")
println(numbers union setOf("four", "five"))
println(setOf("four", "five") union numbers)
println(numbers intersect setOf("two", "one"))
println(numbers subtract setOf("three", "four"))
println(numbers subtract setOf("four", "three")) // 相同的输出
[one, two, three, four, five]
[four, five, one, two, three]
[one, two]
[one, two]
[one, two]
Map
参考连接: https://book.kotlincn.net/text/collections-overview.html
以上是关于Kotlin 集合List SetMap操作汇总的主要内容,如果未能解决你的问题,请参考以下文章
Kotlin集合操作 ① ( List 创建与元素获取 | 安全获取集合元素 | getOrElse | getOrNull )
Kotlin集合操作 ① ( List 创建与元素获取 | 安全获取集合元素 | getOrElse | getOrNull )
Kotlin集合操作总结 ( List 集合 | MutableList 集合 | List 集合遍历 | Set 集合 | MutableSet 集合 | Map 集合 | 可变 Map集合 )
Kotlin集合操作总结 ( List 集合 | MutableList 集合 | List 集合遍历 | Set 集合 | MutableSet 集合 | Map 集合 | 可变 Map集合 )