kotlin ——集合使用

发布时间:2024年01月04日

一、集合的使用

1、不可变集合

  val listString= listOf<String>("one","two","one")
    println(listString)
    
    输出:[one, two, one]

// set集合去重
    val setString= setOf<String>("one","two","one")
    println(setString)
    
    输出:[one, two]

2、可变集合

 val numbers= mutableListOf<Int>(1,2,3,4)
    numbers.add(6)
    numbers.removeAt(1)
    numbers[0]=10
    println(numbers)
    
输出:[10, 3, 4, 6]

//    set集合自动过滤重复元素
    val hello= mutableSetOf<String>("h","e","l","l","o")
    hello.remove("o")
    println(hello)
    
输出:[h, e, l]

//集合的加减操作:

    hello+=setOf("0","w","o","r","l","d")
    
    输出: [h, e, l, 0, w, o, r, d]

3、Map集合

   val numberMap= mapOf<String,Int>("a" to 1,"b" to 2,"c" to 3,"d" to 4)
    println("keys:${numberMap.keys}")
    println("values:${numberMap.values}")

    if ("a" in numberMap.keys){}
    if (2 in numberMap.values){}

输出: 
keys:[a, b, c, d]
values:[1, 2, 3, 4]

二、集合的排序

1、随机排序

 val number2= mutableListOf<Int>(12,25,20,56,28)
//    随机排序
    number2.shuffled()
    println("随机$number2")
    输出:随机[12, 25, 20, 56, 28]

2、从小到大

//    从小到大排序
    number2.sort()
    println("小大${number2}")
    输出:小大[12, 20, 25, 28, 56]

3、从大到小

//    从大到小排序
    number2.sortedDescending()
    println("大小${number2.sortedDescending()}")
    输出:大小[56, 28, 25, 20, 12]

4、条件排序

  data class Language(var name:String,var score:Int)

    val languageList = mutableListOf<Language>()
    languageList.add(Language("java",88))
    languageList.add(Language("kotlin",98))
    languageList.add(Language("c语言",86))
    languageList.add(Language("python",80))
    languageList.add(Language("javascript",80))

//    sortBy单条件排序
    languageList.sortBy { it.score }
    println(languageList)
    输出:[Language(name=python, score=80), Language(name=javascript, score=80), Language(name=c语言, score=86), Language(name=java, score=88), Language(name=kotlin, score=98)]

//   sortWith 多条件排序
    languageList.sortWith(compareBy({it.score},{it.name}))
    println(languageList)
    输出:[Language(name=javascript, score=80), Language(name=python, score=80), Language(name=c语言, score=86), Language(name=java, score=88), Language(name=kotlin, score=98)]
文章来源:https://blog.csdn.net/qq_26554909/article/details/135383501
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。