当前位置:网站首页>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
边栏推荐
- C#/VB. Net word to text
- 根据先序遍历和中序遍历生成后序遍历
- The Sandbox 归属周来啦!
- SAVE: 软件分析验证和测试平台
- [js] 去除小数点后面多余的零
- How to judge the video frame type in h265 in golang development
- Notes to nodejs (II)
- Reconstruct the backbone of the supply chain and realize lean production in the LED lighting industry
- How can manufacturing enterprises go to the cloud?
- What to check for AIX system monthly maintenance (II)
猜你喜欢
云原生流水线工具汇总

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

Summary of some indicators for evaluating and selecting the best learning model

Flutter中的GetX状态管理用起来真的那么香吗?

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

开发协同,高效管理 | 社区征文

Talking about the knowledge of digital transformation

Ant won the finqa competition champion and made a breakthrough in AI technology of long text numerical reasoning

谈谈数字化转型晓知识
![[observation] Dell technology + Intel aoteng Technology: leading storage innovation with](/img/cf/3e3eb6389693667edad534b556c15c.png)
[observation] Dell technology + Intel aoteng Technology: leading storage innovation with "nanosecond speed"
随机推荐
Installation and use of qingscan scanner
如何利用数仓创建时序表
Summary of some indicators for evaluating and selecting the best learning model
Deserialization - PHP deserialization
浩哥的博客之路
MySQL事務隔離
What is the development prospect of face recognition technology?
Cause analysis and Countermeasures for FANUC robot srvo-050 collision detection alarm (available for personal test)
专业“搬砖”老司机总结的 12 条 SQL 优化方案,非常实用!
Ambire 指南:Arbitrum 奥德赛活动开始!第一周——跨链桥
【设计】1359- Umi3 如何实现插件化架构
数据解读!理想L9冲刺「月销过万」,从BBA手中抢份额
C# 读取内存条占用大小,硬盘占用大小
go语言学习
Docker中部署Redis集群与部署微服务项目的详细过程
PHP时间戳
How to handle the IP inconsistency in the contact when easygbs is cascaded with the upper level
CS5213 HDMI转VGA带音频信号输出方案
Phpmailer sends mail PHP
Micro build low code tutorial - Application creation