当前位置:网站首页>Kotlin 集合List 、Set、Map操作汇总
Kotlin 集合List 、Set、Map操作汇总
2022-06-23 22:03:00 【黄毛火烧雪下】
一、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
边栏推荐
- 【技术干货】蚂蚁办公零信任的技术建设路线与特点
- Postman可以集成到CI,CD流水线中做自动化接口测试吗?
- How to judge the video frame type in h265 in golang development
- Generate post order traversal according to pre order traversal and mid order traversal
- The fortress machine installs pytorch, mmcv, and mmclassification, and trains its own data sets
- Save: software analysis, verification and test platform
- 如何利用数仓创建时序表
- Is Everbright futures safe? What do I need to open an account?
- Talking about the knowledge of digital transformation
- AIX系统月维护查什么(一)
猜你喜欢

Section 30 high availability (HA) configuration case of Tianrongxin topgate firewall

Save: software analysis, verification and test platform

什么是免疫组织化学实验? 免疫组织化学实验

kubernetes之常用核心资源对象

Data interpretation! Ideal L9 sprints to "sell more than 10000 yuan a month" to grab share from BBA

【设计】1359- Umi3 如何实现插件化架构
![[design] 1359- how umi3 implements plug-in architecture](/img/f1/c4cb7715aff7f10d099e4f11b32c01.png)
[design] 1359- how umi3 implements plug-in architecture

The sandbox and bayz have reached cooperation to jointly drive the development of metauniverse in Brazil

国内外最好的12款项目管理系统优劣势分析

微信视频号如何用 PC 电脑做直播?
随机推荐
专业“搬砖”老司机总结的 12 条 SQL 优化方案,非常实用!
The Sandbox 与 BAYZ 达成合作,共同带动巴西的元宇宙发展
Bilibili × Blue bridge cloud course | online programming practice competition is new!
How to set up a website construction map
根据先序遍历和中序遍历生成后序遍历
Industry 4.0 era: the rise of low code may bring about changes in the pattern of manufacturing industry
Can postman be integrated into Ci and CD pipelines for automated interface testing?
sql server常用sql
开发协同,高效管理 | 社区征文
Oracle关闭回收站
PHP的curl功能扩展基本用法
Urgent! Tencent cloud container security supports the detection of Apache log4j2 vulnerabilities for the first time. It is in free trial
The fortress computer is connected to the server normally, but what's wrong with the black screen? What should I do?
The national post office and other three departments: strengthen the security management of personal information related to postal express delivery, and promote the de identification technology of per
The latest February activity # 1 core 2G first year: 38 yuan / year! 2-core 4G light weight RMB 74 / year! Mysql database 19.9 yuan / year!!
Million message IM system technical points sharing
Desai wisdom number - histogram (basic histogram): the way to celebrate father's day in 2022
Aicon2021 | AI technology helps content security and promotes the healthy development of Internet Environment
谈谈数字化转型晓知识
Three ways to enable IPv6 on Tencent cloud