当前位置:   article > 正文

Kotlin->Kotlin集合操作_kotlin 函数 removefirstornull

kotlin 函数 removefirstornull

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 集合过滤
// 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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 集合转换
// 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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101

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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/576041
推荐阅读
相关标签
  

闽ICP备14008679号