Kotlin->Kotlin集合操作

1. 创建集合

// 创建List
val list = listOf(1, 2, 3) // 不可读写的ArrayList
val arrayList = arrayListOf(1, 2, 3) //ArrayList
val mutableList = mutableListOf(1, 2, 3) // ArrayList

// 创建Set
val set = setOf(1, 2, 3) // 去重不可读写的LinkedHashSet
val hashSet = hashSetOf(1, 2, 3) // 去重的HashSet
val mutableSet = mutableSetOf(1, 2, 3) // // 去重可读写的LinkedHashSet

// 创建Map
val map = mapOf("a" to 1, "b" to 2) // 去重不可读写的LinkedHashMap
val hashMap = hashMapOf("a" to 1, "b" to 2)// 去重的HashMap
val mutableMap = mutableMapOf("a" to 1, "b" to 2) // 去重可读写的LinkedHashMap

2. 集合转换

  • 集合的增删查改、计算
// 增加
var arrayList = arrayListOf(1, 2, 3)
arrayList.add(4) // List末尾增加
arrayList.add(0, 5) // List指定索引位置增加
arrayList.addFirst(6) // List开头增加
arrayList.addLast(7) // List末尾增加
arrayList.addAll(arrayListOf(8)) // List末尾添加集合
println(arrayList)
// 打印结果:
[6, 5, 1, 2, 3, 4, 7, 8]

// 删除
var arrayList = arrayListOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
arrayList.remove(3) // 删除3这个值
arrayList.removeAt(0) // 删除指定索引的值
arrayList.removeFirst() // 删除第一个元素失败,会抛出异常
arrayList.removeFirstOrNull()  // 删除失败,会null
arrayList.removeLast() // 删除最后一个元素失败,会抛出异常
arrayList.removeLastOrNull()
arrayList.removeAll(arrayListOf(2, 3))
println(arrayList)
arrayList.clear() // 清空集合
// 打印结果:
[5, 6, 7]

// 查找
arrayList[0] // 索引查找
arrayList.indexOf(1) // 查找元素第一次出现的索引, 如果没有则返回-1
arrayList.lastIndexOf(1) // 查找元素最后一次出现的索引, 如果没有则返回-1
arrayList.indexOfFirst { true } // 查找第一个符合条件的元素索引
arrayList.indexOfLast { true } // 查找最后一个符合条件的元素索引
arrayList.firstNotNullOf {  } // 查找第一个非空元素,如果没有则抛出异常
arrayList.firstNotNullOfOrNull {  } // 查找第一个非空元素,如果没有则返回null

// 修改
arrayList[0] = 1 // 修改指定索引的值

// count、maxOrNull、minOrNull、average、sum
val numbers = listOf(6, 42, 10, 4)
println("Count: ${numbers.count()}")
println("Max: ${numbers.maxOrNull()}")
println("Min: ${numbers.minOrNull()}")
println("Average: ${numbers.average()}")
println("Sum: ${numbers.sum()}")
// 打印结果:
Count: 4
Max: 42
Min: 4
Average: 15.5
Sum: 62
  • 集合过滤
// List过滤
val fruits = listOf("banana", "avocado", "apple", "kiwifruit")
fruits.filter { it.startsWith("a") }
        .sortedBy { it }
        .map { it.toUpperCase() }
        .forEach { println(it) }   
// 打印结果:
APPLE
AVOCADO

// Map过滤
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredKeysMap = numbersMap.filterKeys { it.endsWith("1") }
val filteredValuesMap = numbersMap.filterValues { it < 10 }
println(filteredKeysMap)
println(filteredValuesMap)
// 打印结果:
{key1=1, key11=11}
{key1=1, key2=2, key3=3}

// 过滤实例
val numbers = listOf(null, 1, "two", 3.0, "four")
println("All String elements in upper case:")
numbers.filterIsInstance<String>().forEach {
    println(it.toUpperCase())
}
// 打印结果:
All String elements in upper case:
TWO
FOUR
  • 集合转换
// List拉伸:flatten、joinToString、joinTo
val numberSets = listOf(setOf(1, 2, 3), setOf(4, 5, 6), setOf(1, 2))
println(numberSets.flatten())
// 打印结果:
[1, 2, 3, 4, 5, 6, 1, 2]

val numbers = listOf("one", "two", "three", "four") 
val listString = StringBuffer("The list of numbers: ")
numbers.joinTo(listString)
println(listString)
println(numbers.joinToString(separator = " | ", prefix = "start: ", postfix = ": end"))
// 打印结果:
[one, two, three, four]
one, two, three, four
The list of numbers: one, two, three, four
start: one | two | three | four: end

// List切片:slice、chunked、groupBy、partition、associateBy
// slice
val numbers = listOf("one", "two", "three", "four", "five", "six")    
println(numbers.slice(1..3))
println(numbers.slice(0..4 step 2))
println(numbers.slice(setOf(3, 5, 0)))    
// 打印结果:
[two, three, four]
[one, three, five]
[four, six, one]

// chunked
val numbers = (0..13).toList() 
println(numbers.chunked(3) { it.sum() })  // it 为原始集合的一个块
// 打印结果:
[3, 12, 21, 30, 25]

// groupBy
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.groupBy { it.first().toUpperCase() })
println(numbers.groupBy(keySelector = { it.first() }, valueTransform = { it.toUpperCase() }))
/// 打印结果:
{O=[one], T=[two, three], F=[four, five]}
{o=[ONE], t=[TWO, THREE], f=[FOUR, FIVE]}

// partition
val numbers = listOf("one", "two", "three", "four")
val (match, rest) = numbers.partition { it.length > 3 }
println(match)
println(rest)
// 打印结果:
[three, four]
[one, two]

// associateBy
val numbers = listOf("one", "two", "three", "four")
println(numbers.associateBy { it.first().toUpperCase() })
println(numbers.associateBy(keySelector = { it.first().toUpperCase() }, valueTransform = { it.length }))
// 打印结果:
{O=one, T=three, F=four}
{O=3, T=5, F=4}

// List映射:zip
// zip
val colors = listOf("red", "brown", "grey")
val animals = listOf("fox", "bear", "wolf")
val twoAnimals = listOf("fox", "bear")
println(colors zip animals)
println(colors.zip(twoAnimals))

// 打印结果:
[(red, fox), (brown, bear), (grey, wolf)]
[(red, fox), (brown, bear)]

// List检验:any、none、all
val numbers = listOf("one", "two", "three", "four")
//any:至少有一个元素匹配给定谓词
println(numbers.any { it.endsWith("e") })
//none:没有元素与给定谓词匹配
println(numbers.none { it.endsWith("a") })
//all:所有元素都匹配给定谓词
println(numbers.all { it.endsWith("e") })
// 打印结果:
true
true
false

// 集合去重
// union:A元素 + B元素,A.addAll(B)的效果,但去重了
// intersect(取交集)与 retainAll 功能相同:取A中和B相同的元素,即相同的输出
// subtract:A中去掉和B相同的元素,即不相同的输出
val numbers = setOf("one", "two", "three", "four")

println(numbers union setOf("four", "five"))// A元素 + B元素,A.addAll(B)的效果,但去重了
println(setOf("four", "five") union numbers)
println(numbers intersect setOf("two", "one"))// 取A中和B相同的元素,即相同的输出
println(numbers subtract setOf("three", "four"))// A中去掉和B相同的元素,不相同的输出
println(numbers subtract setOf("four", "three")) 
// 打印结果:
[one, two, three, four, five]
[four, five, one, two, three]
[one, two]
[one, two]
[one, two]

3. 集合排序

// 固定排序:sort、sortDescending
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sort()
println("Sort into ascending: $numbers")
numbers.sortDescending()
println("Sort into descending: $numbers")
// 打印结果:
Sort into ascending: [four, one, three, two]
Sort into descending: [two, three, one, four]

// 自定义排序:sortBy、sortByDescending、sortedWith
// sortBy、sortByDescending
numbers.sortBy { it.length }
println("Sort into ascending by length: $numbers")
numbers.sortByDescending { it.last() }
println("Sort into descending by the last letter: $numbers")
// 打印结果
Sort into ascending by length: [two, one, four, three]
Sort into descending by the last letter: [four, two, one, three]

// sortedWith
// Comparator {}lambda表达式中有三种返回值:
// 1. >0, 表示升序排列
// 2. <0, 表示降序排列
// 3. =0, 不排序
val lengthComparator = Comparator { str1: String, str2: String -> str1.length - str2.length }
println(listOf("aaa", "bb", "c").sortedWith(lengthComparator))
// 打印结果:
[c, bb, aaa]
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值