• kotlin--3.集合操作


    目录

    一.list集合

    二.Set集合

     三.Map集合

    迭代遍历Map集合:

      8.hashMap

    四.Stream流

    1.map

    2.filter 

    3.reduce 

    4.forEach 

    5.sorted 

    6.distinct 

     7.综合案例


    一.list集合

    在Kotlin中,常见的List集合类型有以下几种:

    1. listOf:不可变的只读List,其元素不可更改。
    2. mutableListOf:可变的List,允许添加、删除和修改元素。
    3. arrayListOf:可变的List,底层实现使用数组,性能较好。

    以下是创建List集合以及常见操作的示例:

    1. 创建List集合:
    1. // 创建一个不可变的只读List
    2. val list1 = listOf(1, 2, 3)
    3. println(list1) // 输出:[1, 2, 3]
    4. // 创建一个可变的List
    5. val list2 = mutableListOf("apple", "banana", "orange")
    6. println(list2) // 输出:[apple, banana, orange]
    7. // 创建一个可变的ArrayList
    8. val list3 = arrayListOf(1.2, 3.4, 5.6)
    9. println(list3) // 输出:[1.2, 3.4, 5.6]

       2.常见操作:

    1. val numbers = listOf(1, 2, 3, 4, 5)
    2. // 访问元素
    3. val firstNumber = numbers[0]
    4. println(firstNumber) // 输出:1
    5. // 添加元素
    6. val newList = numbers.toMutableList()
    7. newList.add(6)
    8. println(newList) // 输出:[1, 2, 3, 4, 5, 6]
    9. // 删除元素
    10. newList.removeAt(2)
    11. println(newList) // 输出:[1, 2, 4, 5, 6]
    12. // 修改元素
    13. newList[1] = 10
    14. println(newList) // 输出:[1, 10, 4, 5, 6]
    15. // 迭代元素
    16. for (number in numbers) {
    17. println(number)
    18. }
    19. // 过滤元素
    20. val evenNumbers = numbers.filter { it % 2 == 0 }
    21. println(evenNumbers) // 输出:[2, 4]

    3.泛型约束

    例如,在创建一个只包含整数的List时,可以指定List的泛型类型为Int:

    1. val numbers: List<Int> = listOf(1, 2, 3)
    2. val mutableNumbers: MutableList<Int> = mutableListOf(1, 2, 3)

    二.Set集合

    Kotlin中的Set集合是一种不允许重复元素的集合。由于Set集合中的元素是无序的,因此不能通过索引获取元素。

    1.创建Set集合:

    1. val set: Set<Int> = setOf(1, 2, 3)
    2. val mutableSet: MutableSet<Int> = mutableSetOf(1, 2, 3)

    2.Set集合的常见操作:

    • 添加元素:使用add方法添加元素到Set集合中。
      mutableSet.add(4)
    • 删除元素:使用remove方法从Set集合中删除指定元素。
      mutableSet.remove(3)
    • 判断元素是否存在:使用contains方法判断Set集合中是否包含指定元素。
      val containsElement = mutableSet.contains(2)
    • 获取Set集合的大小:使用size属性获取Set集合的大小。
      val size = mutableSet.size
    • 迭代遍历Set集合:
      1. for (element in mutableSet) {
      2. println(element)
      3. }
      4. ---------------------
      5. mutableSet.forEach { element ->
      6. println(element)
      7. }

     三.Map集合

    在Kotlin中,Map集合用于存储键值对,其中键和值可以是任意类型。以下是创建Map集合和进行常见操作的示例:

    1. 创建Map集合:

      • 使用mapOf函数创建不可变的Map集合:
        val map: MapInt> = mapOf("A" to 1, "B" to 2, "C" to 3)
      • 使用mutableMapOf函数创建可变的Map集合:
        val mutableMap: MutableMapInt> = mutableMapOf("A" to 1, "B" to 2, "C" to 3)
    2. Map集合的常见操作:

      • 添加或更新元素:使用put方法添加或更新键值对。
        1. mutableMap.put("D", 4)
        2. mutableMap["E"] = 5
      • 删除元素:使用remove方法从Map集合中删除指定键值对。
        mutableMap.remove("C")
      • 判断键是否存在:使用containsKey方法判断Map集合中是否包含指定键。
        val containsKey = mutableMap.containsKey("A")
      • 判断值是否存在:使用containsValue方法判断Map集合中是否包含指定值。
        val containsValue = mutableMap.containsValue(2)
      • 获取Map集合的大小:使用size属性获取Map集合的大小。
        val size = mutableMap.size
      • 获取键或值的集合:使用keys和values属性分别获取Map集合中的键和值的集合。
        1. val keys = mutableMap.keys
        2. val values = mutableMap.values
      • 迭代遍历Map集合:

        1. for ((key, value) in mutableMap) {
        2. println("Key: $key, Value: $value")
        3. }
        4. ---------------------
        5. mutableMap.forEach { (key, value) ->
        6. println("Key: $key, Value: $value")
        7. }

      8.hashMap

    1. fun main() {
    2. val hashMap = HashMapInt>()
    3. // 添加键值对
    4. hashMap["Alice"] = 25
    5. hashMap["Bob"] = 30
    6. hashMap["Charlie"] = 35
    7. // 获取键对应的值
    8. val age = hashMap["Alice"]
    9. println(age) // 输出: 25
    10. // 遍历键值对
    11. for ((name, age) in hashMap) {
    12. println("$name: $age")
    13. }
    14. // 输出:
    15. // Alice: 25
    16. // Bob: 30
    17. // Charlie: 35
    18. // 检查键是否存在
    19. val containsKey = hashMap.containsKey("Alice")
    20. println(containsKey) // 输出: true
    21. // 删除指定键值对
    22. hashMap.remove("Bob")
    23. println(hashMap) // 输出: {Alice=25, Charlie=35}
    24. // 清空哈希表
    25. hashMap.clear()
    26. println(hashMap.isEmpty()) // 输出: true
    27. }

    四.Stream流

    在Kotlin中,Stream流操作提供了一种功能强大的方式来处理集合数据。可以使用扩展函数和lambda表达式来对集合进行处理。以下是一些常见的Stream流操作方法及其示例:

    1.map

    1. map对集合中的每个元素应用函数,并将结果收集到一个新的集合中。
    1. val numbers = listOf(1, 2, 3, 4, 5)
    2. val squaredNumbers = numbers.map { it * it }
    3. println(squaredNumbers) // 输出:[1, 4, 9, 16, 25]

    2.filter 

    1. filter:根据指定的条件筛选集合中的元素。
    1. val numbers = listOf(1, 2, 3, 4, 5)
    2. val evenNumbers = numbers.filter { it % 2 == 0 }
    3. println(evenNumbers) // 输出:[2, 4]

    3.reduce 

    1. reduce:将集合中的元素进行累积操作,返回一个结果。
    1. val numbers = listOf(1, 2, 3, 4, 5)
    2. val sum = numbers.reduce { acc, num -> acc + num }
    3. println(sum) // 输出:15

    4.forEach 

    1. forEach:对集合中的每个元素应用指定的操作。
    1. val numbers = listOf(1, 2, 3, 4, 5)
    2. numbers.forEach { println(it) }

    5.sorted 

    1. sorted:对集合中的元素进行排序。
    1. val numbers = listOf(4, 2, 5, 1, 3)
    2. val sortedNumbers = numbers.sorted()
    3. println(sortedNumbers) // 输出:[1, 2, 3, 4, 5]

    6.distinct 

    1. distinct去除集合中的重复元素。
    1. val numbers = listOf(1, 2, 2, 3, 3, 3, 4, 4, 5)
    2. val distinctNumbers = numbers.distinct()
    3. println(distinctNumbers) // 输出:[1, 2, 3, 4, 5]

     7.综合案例

    1. data class Person(val name: String, val age: Int)
    2. fun main() {
    3. val people = listOf(
    4. Person("Alice", 25),
    5. Person("Bob", 30),
    6. Person("Charlie", 35),
    7. Person("David", 40),
    8. Person("Emma", 45)
    9. )
    10. val filteredPeople = people.filter { it.age > 30 }
    11. .sortedByDescending { it.age }
    12. .map { "${it.name} (${it.age})" }
    13. println(filteredPeople)
    14. }

    在上述案例中,我们有一个包含Person对象的人员列表。我们首先使用filter函数筛选出年龄大于30岁的人员,然后使用sortedByDescending函数按年龄降序排序,最后使用map函数将Person对象转换为格式化的字符串。最终,我们将过滤和格式化后的结果打印出来。

    输出结果将是:

    [Emma (45), David (40), Charlie (35)]
  • 相关阅读:
    【SpringCloud】微服务技术栈入门3 - Gateway快速上手
    CCF CSP认证历年题目自练 Day40
    Java处理日期
    CSS常见选择器
    Java23种设计模式-结构型模式之桥接模式
    因为过人的汇报能力,新员工被领导点名夸奖!
    为什么应该尽可能避免在静态构造函数中初始化静态字段?
    了解网络黑客的关键攻击方法
    Environment与ConfigurableEnvironment
    【kubernetes】使用CloudProvider对接云厂商的LB
  • 原文地址:https://blog.csdn.net/jjhnb123/article/details/134471424