kotlin 添加第一个 集合_Kotlin常用数据结构

一.数组

Kotlin为数组增加了一个Array类,为元素是基本类型的数组增加了XxxArray类,如IntArray,FloatArray等。Kotlin的数组使用Array类代表,Kotlin数组就是一个Array类的实例,所以Kotlin数组也算是引用类型。

1.创建

 在kotlin中,既可以使用arrayOf()、arrayOfNulls()、emptyArray()工具函数创建数组,也可以使用Array(size:Int,init:(Int)->T)构造器创建数组。

Kotlin专门提供了ByteArray、ShortArray、IntArray、LongArray、CharArray、FloatArray、DoubleArray、BooleanArray,分别用于映射Java的byte[]、short[]、int[]、long[]、char[]、float[]、double[]、boolean[]这8种基本类型的数组。

var array1 = arrayOf(1,10,4,6,15)var array2= arrayOf(1,10,4, "Ajax","Prake")var array3 = emptyArray<Int>() //长度为0的空数组var array4 = arrayOfNulls<Int>(5) //数组大小为5,数组元素全部为null//使用构造器创建var array5=Array(6,{"hello"})val array6 = Array(5) { i -> (i * i).toString() }  //创建跟索引关联的数组//创建包含指定元素的数组var intArr = intArrayOf(2, 4, 30, -5)var doubleArr = doubleArrayOf(2.3, 3.5, -3.0)//创建指定长度、使用Lambda表达式初始化数组元素的数组var intArr2 = IntArray(5, { it * it })var charArr = CharArray(5, { (it * 2 + 97).toChar() })

2.修改和访问

Kotlin数组有set()和get()函数,可以直接修改和访问数组的元素,也可以通过方括号[]访问和修改,如访问第一个元素array[0]。

fun main(args: Array<String>) {    val array1 = arrayOf(1,2,3,4)    array1.set(0,5)  //方法 1    array1[2] = 6     //方法 2    for(element in array1){        println(element)    }}输出:5264

3.遍历

kotlin中利用for-in循环的多种样式遍历数组,如下所示:

fun main(args: Array<String>){    var array: IntArray = intArrayOf(5,10,20,12,15)      array.forEach {  //方法 1        println(it)    }      for(element in array){  //方法 2        println(element)    }        for (index in array.indices){  //方法 3        println(array[index])    }    for((index,value) in array.withIndex()){  //方法 4        println("the element at $index is $value")    }}输出:510201215510201215510201215the element at 0 is 5the element at 1 is 10the element at 2 is 20the element at 3 is 12the element at 4 is 15

4.排序和反转

kotlin中,为数组提供了一些排序和反转接口,如sort(),sortDescending(),reverse()等。

var array = arrayOf(10,2,33,42)array.sort() //自然顺序排序array.forEach {    println(it)}array.sortDescending()array.forEach {    println(it)}array.reverse() // 数组反转array.forEach {    println(it)}输出:210334242331022103342

5.转换

Kotlin 标准库为数组转换提供了一组扩展函数。这些函数根据提供的转换规则从现有数组中构建新数组;

var array = intArrayOf(1,2,3,4)var array1 = array.map { it * 2 }   //元素的2倍println(array1)var array2 = array.mapIndexed { index, i -> index * i }  //元素和索引的积println(array2)输出:[2, 4, 6, 8][0, 2, 6, 12]

6.过滤

Kotlin也为数组提供了过滤接口,过滤条件由条件定义——接受一个数组元素并且返回布尔值的 lambda 表达式:true 说明给定元素与条件匹配,false 则表示不匹配。

var array = intArrayOf(10,21,13,4)var array1 = array.filter { it >= 13 } //过滤 元素值大于等于13的元素println(array1)var array2 = array.filterIndexed { index, i -> index >= 2 && i > 12 } println(array2)输出:[21, 13][13]

二.集合

Kotlin 标准库提供了一整套用于管理集合的工具,集合是包含相同类型,可变数量(数目可为零)的一组对象。

下面是 Kotlin 集合接口的图表:

7230e343fd5e09d77b1d5a35719d6142.png

1.List

List是Kotlin 标准库中最常用的集合类型。它以指定的顺序存储元素(元素可以为空值),并提供使用索引访问元素的方法。在 Kotlin 中,List 的默认实现是 ArrayList;MutableList 是可以进行写操作的 List,例如用于在特定位置添加或删除元素。

(1)创建

在kotlin中,可以使用库函数 listOf(),emptyList()以及具体类型的构造函数等来创建一个List集合并传递元素值给它。

下面是创建List的多种方法:

val list = listOf("one", "two", "three", "four") //只读val mutableList = mutableListOf("one", "two", "three", "four") //构造可操作的集合val emptyList = emptyList() //创建空集合val doubledList = List(3, { it * 2 }) //构建根据索引值定义元素的值。val copyList = doubledList.toMutableList() //copy,创建可操作集合val readOnlyCopyList = doubledList.toList() //copy,创建只读集合val longerThan3 = list.filter { it.length > 3 } //过滤列表会创建与过滤器匹配的新元素列表// 具体类型的构造函数val linkedList = LinkedList(listOf("one", "two", "three"))val  arrayList = ArrayList(listOf("one", "two", "three"))

(2)增删改查

在kotlin中,为List提供多种增删改查的接口,访问和修改元素可以使用get和set方法,也可以用方括号[]实现,如下所示:

val list = mutableListOf(1, 2, 3, 4)val list2 = mutableListOf(5, 6, 7, 8)list.add(0)//增加println(list)list.addAll(list2)//添加list2集合println(list)list[0] = 100 //修改println(list)list.set(1,200) //修改println(list)println(list[0]) //查找println(list.get(0)) //查找println(list.indexOf(5)) //从头查找,返回元素5在列表中的位置println(list.lastIndexOf(2)) //从尾部查找,返回元素5在列表中的位置println(list.indexOfFirst { it > 2}) //返回与条件匹配的第一个元素的索引,如果没有此类元素,则返回 -1println(list.indexOfLast { it % 2 == 1}) //返回与条件匹配的最后一个元素的索引,如果没有此类元素,则返回 -1list.removeAt(1) //删除println(list)list.remove(8) //删除println(list)list.clear() //清空println(list)输出:[1, 2, 3, 4, 0][1, 2, 3, 4, 0, 5, 6, 7, 8][100, 2, 3, 4, 0, 5, 6, 7, 8][100, 200, 3, 4, 0, 5, 6, 7, 8]1001005-107[100, 3, 4, 0, 5, 6, 7, 8][100, 3, 4, 0, 5, 6, 7][]

(3)遍历

kotlin中利用for-in循环和迭代器为List集合提供了多种方法遍历,如下所示:

val list = listOf("one", "two", "three", "four")list.forEach {     println(it)}for(element in list){     println(element)}for(index in list.indices){     println(list[index])}var iterator = list.listIterator()while (iterator.hasNext()){var element = iterator.next()     println(element)}for((index,value) in list.withIndex()){     println("the element at $index is $value")}输出:onetwothreefouronetwothreefouronetwothreefouronetwothreefourthe element at 0 is onethe element at 1 is twothe element at 2 is threethe element at 3 is four

(4)排序

-  自然顺序

kotlin提供了基本的排序函数 sorted() 和 sortedDescending() ,这些函数按照其自然顺序升序或者降序。

val numbers = listOf("one", "two", "three", "four")println("Sorted ascending: ${numbers.sorted()}")println("Sorted descending: ${numbers.sortedDescending()}")输出:Sorted ascending: [four, one, three, two]Sorted descending: [two, three, one, four]

-  反转

① reversed() :函数以相反的顺序检索集合。

val numbers = listOf("one", "two", "three", "four")println(numbers.reversed())输出:[four, three, two, one]

注意:

(1) 反转不等于倒序;

(2) reversed() 返回带有元素副本的新集合。因此,如果你之后改变了原始集合,这并不会影响先前获得的 reversed() 的结果。

② asReversed():返回相同集合实例的一个反向视图,如果原始列表发生变化,那么它也会相应发生变化。

val numbers = listOf("one", "two", "three", "four")val reversedNumbers = numbers.asReversed()println(reversedNumbers)输出:[four, three, two, one]
val numbers = mutableListOf("one", "two", "three", "four")val reversedNumbers = numbers.asReversed()println(reversedNumbers)numbers.add("five")println(reversedNumbers)输出:[four, three, two, one][five, four, three, two, one]

-  自定义顺序

kotlin集合提供了排序函数 sortedBy() 和 sortedByDescending()。它们接受一个将集合元素映射为 Comparable 值的选择器函数,并以该值的自然顺序对集合进行升序或降序。

val numbers = listOf("one", "two", "three", "four")val sortedNumbers = numbers.sortedBy { it.length }println("Sorted by length ascending: $sortedNumbers")val sortedByLast = numbers.sortedByDescending { it.last() }println("Sorted by the last letter descending: $sortedByLast")输出:Sorted by length ascending: [one, two, four, three]Sorted by the last letter descending: [four, two, one, three]

也可以提供自己的 Comparator。为此,调用传入 Comparator 的 sortedWith() 函数。

例如, 使用此函数,按照字符串长度排序如下所示:

val numbers = listOf("one", "two", "three", "four")val sortList = numbers.sortedWith(compareBy { it.length })val sortDescendList = numbers.sortedWith(compareByDescending { it.length })println(sortList)println(sortDescendList)输出:[one, two, four, three][three, four, one, two]

(5)转换

Kotlin 标准库为List集合转换提供了一组扩展函数, 这些函数根据提供的转换规则从现有集合中构建新集合:

var list = mutableListOf(1, 2, 3, 4)println(list)var list2 = list.map {      it * 2}println(list2)var list3 = list.mapIndexed { index, i ->      index * i}println(list3)输出:[1, 2, 3, 4][2, 4, 6, 8][0, 2, 6, 12]

(6)过滤

在Kotlin中,过滤条件由条件定义——接受一个集合元素并且返回布尔值的 lambda 表达式:true 说明给定元素与条件匹配,false 则表示不匹配。

val numbers = listOf("one", "two", "three", "four")  val longerThan3 = numbers.filter { it.length > 3 }println(longerThan3)val filteredIdx = numbers.filterIndexed { index, s -> (index != 0) && (s.length < 5)  }val filteredNot = numbers.filterNot { it.length <= 3 }//使用否定条件来过滤集合println(filteredIdx)println(filteredNot)val numbers2 = listOf(null, 1, "two", 3.0, "four")numbers2.filterIsInstance().forEach { //通过过滤给定类型的元素来缩小元素的类型,这里只对字符串做处理         println(it.toUpperCase())}输出:[three, four][two, four][three, four]TWOFOUR

2.Set

kotlin中,Set 存储唯一的元素,它们的顺序是不确定的(null 元素也是唯一的,一个 Set 只能包含一个 null)。

(1)创建

在kotlin中,可以使用库函数 setOf(),emptySet(),mutableSetOf()以及具体的构造函数等来创建一个Set集合并传递元素值给它。

val set = setOf(1, 2, 3, 4)//只读val mutableSet = mutableSetOf(1,2,3,4) //构造可操作的集合val emptySet = emptySet<Int>()//创建空集合val copySet = set.toMutableSet()//copy,创建可操作集合val readOnlyCopyList = mutableSet.toSet()//copy,创建只读集合val longerThan3 = set.filter { it >= 3 } //过滤列表会创建与过滤器匹配的新元素列表// 具体类型的构造函数val hashSet = hashSetOf(1, 2, 3, 4) //无序,不保留元素插入的顺序val linkedSet = linkedSetOf(1,2,3,4) //有序,保留元素插入的顺序

(2)增删改查

在kotlin中,为Set提供多种增删改查的接口,如下所示:

val set = mutableSetOf(1, 2, 3, 4)val set2 = mutableSetOf(5, 6, 7, 8)set.add(5)//增加println(set)set.addAll(set2)//添加list2println(set)println(set.indexOf(5)) //从头查找,返回元素5在列表中的位置println(set.lastIndexOf(2)) //从尾部查找,返回元素5在列表中的位置println(set.indexOfFirst { it > 2 }) //返回与条件匹配的第一个元素的索引,如果没有此类元素,则返回 -1println(set.indexOfLast { it % 2 == 1 }) //返回与条件匹配的最后一个元素的索引,如果没有此类元素,则返回 -1set.remove(1) //删除println(set)set.removeAll(set2) //删除println(set)set.clear() //清空println(set)输出:[1, 2, 3, 4, 5][1, 2, 3, 4, 5, 6, 7, 8]4126[2, 3, 4, 5, 6, 7, 8][2, 3, 4][]

(3)遍历

kotlin中利用for-in循环和迭代器为Set集合提供了多种方法遍历,如下所示:

var set = setOf(1,2,3,4,5)set.forEach {    println(it)}for(element in set){    println(element)}var iterator = set.iterator()    while (iterator.hasNext()){       var element = iterator.next()       println(element)}for((index,value) in set.withIndex()){      println("the element at $index is $value")}输出:123451234512345the element at 0 is 1the element at 1 is 2the element at 2 is 3the element at 3 is 4the element at 4 is 5

(4)排序

-  自然顺序

kotlin提供了基本的排序函数 sorted() 和 sortedDescending() ,这些函数按照其自然顺序升序或者降序。

var set = setOf(1,30,10,40,5)var sortSet2 = set.sorted() //自然顺序var descendSortSet = set.sortedDescending()//倒序println(set)println(sortSet2)println(descendSortSet)输出:[1, 30, 10, 40, 5][1, 5, 10, 30, 40][40, 30, 10, 5, 1]

-  反转

① reversed() :函数以相反的顺序检索集合。

val numbers = setOf("one", "two", "three", "four")println(numbers.reversed())输出:[four, three, two, one]

注意:

(1) 反转不等于倒序;

(2) reversed() 返回带有元素副本的新集合。因此,如果你之后改变了原始集合,这并不会影响先前获得的 reversed() 的结果。

-  自定义顺序

kotlin集合提供了排序函数 sortedBy() 和 sortedByDescending()。它们接受一个将集合元素映射为 Comparable 值的选择器函数,并以该值的自然顺序对集合进行升序或降序。

val numbers = setOf("one", "two", "three", "four")val sortedNumbers = numbers.sortedBy { it.length }println(sortedNumbers)val sortedByLast = numbers.sortedByDescending { it.last() }println(sortedByLast)输出:[one, two, four, three][four, two, one, three]

也可以提供自己的 Comparator。为此,调用传入 Comparator 的 sortedWith() 函数。

例如, 使用此函数,按照字符串长度排序如下所示:

val numbers = setOf("one", "two", "three", "four")val sortList = numbers.sortedWith(compareBy { it.length })val sortDescendList = numbers.sortedWith(compareByDescending { it.length })println(sortList)println(sortDescendList)输出:[one, two, four, three][three, four, one, two]

(5)转换

Kotlin 标准库为Set集合转换提供了一组扩展函数, 这些函数根据提供的转换规则从现有集合中构建新集合;

var set = setOf(1,30,10,40,5)println(set)var set2 = set.map {         it * 2}println(set2)var set3 = set.mapIndexed { index, i ->         index * i}println(set3)输出:[1, 30, 10, 40, 5][2, 60, 20, 80, 10][0, 30, 20, 120, 20]

(6)过滤

在Kotlin中,过滤条件由条件定义——接受一个集合元素并且返回布尔值的 lambda 表达式:true 说明给定元素与条件匹配,false 则表示不匹配。

val numbers = setOf("one", "two", "three", "four")val longerThan3 = numbers.filter { it.length > 3 }println(longerThan3)val filteredIdx = numbers.filterIndexed { index, s -> (index != 0) && (s.length < 5)  }val filteredNot = numbers.filterNot { it.length <= 3 }//使用否定条件来过滤集合println(filteredIdx)println(filteredNot)val numbers2 = setOf(null, 1, "two", 3.0, "four")numbers2.filterIsInstance().forEach { //通过过滤给定类型的元素来缩小元素的类型,这里只对字符串做处理          println(it.toUpperCase())}输出:[three, four][two, four][three, four]TWOFOUR

3.Map

kotlin中,Map 存储键-值对的一种集合;键是唯一的,但是不同的键可以与相同的值配对。Map 的默认实现为LinkedHashMap,保留元素插入的顺序,而HashMap不保留元素插入的顺序。

(1)创建

在kotlin中,可以使用库函数 mapOf(),emptyMap()以及具体类型的构造函数等来创建一个数组并传递元素值给它。

val map = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) //只读val mutableMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) //构造可操作的集合val emptyMap = emptyMapInt>() val copyMap = map.toMutableMap() //copy,创建可操作集合val readOnlyCopyMap = mutableMap.toMap() //copy,创建只读集合val keyThan = map.filterKeys { it.length > 3 }//创建与过滤器匹配的新集合val valueThan = map.filterValues { it > 3 }//创建与过滤器匹配的新集合val mapThan = map.filter { it.key.length >3 && it.value < 4 }//创建与过滤器匹配的新集合// 具体类型的构造函数val linkedMap = LinkedHashMap(mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4))//保留元素插入的顺序val  arrayMap = HashMap(mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4))//不保留元素插入的顺序

(2)增删改查

在kotlin中,为Map集合提供多种增删改查的接口,如下所示:

val map = mapOf("six" to 6, "eight" to 8, "nine" to 9, "ten" to 10) //只读val mutableMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4) //构造可操作的集合mutableMap.put("five",5)//增加println(mutableMap)mutableMap.putAll(map)//添加mapprintln(mutableMap)mutableMap["one"] = 100 //修改println(mutableMap)mutableMap.put("two", 200) //修改println(mutableMap)println(mutableMap["one"]) //查找println(mutableMap.get("one")) //查找mutableMap.remove("ten") //删除println(mutableMap)mutableMap.clear() //清空println(mutableMap)输出:{one=1, two=2, three=3, four=4, five=5}{one=1, two=2, three=3, four=4, five=5, six=6, eight=8, nine=9, ten=10}{one=100, two=2, three=3, four=4, five=5, six=6, eight=8, nine=9, ten=10}{one=100, two=200, three=3, four=4, five=5, six=6, eight=8, nine=9, ten=10}100100{one=100, two=200, three=3, four=4, five=5, six=6, eight=8, nine=9}{}

(3)遍历

kotlin中利用for-in循环和迭代器为Map集合提供了多种方法遍历,如下所示:

val map = mapOf("six" to 6, "eight" to 8, "nine" to 9, "ten" to 10) //只读map.forEach {     println(it)}for(element in map){     println(element)}var iterator = map.iterator()while (iterator.hasNext()){      var element = iterator.next()      println(element)}for(key in map.keys){       println(map[key])}map.forEach { key, value ->       println("the element at $key is $value")}for((key,value) in map){       println("the element at $key is $value")}输出:six=6eight=8nine=9ten=10six=6eight=8nine=9ten=10six=6eight=8nine=9ten=1068910the element at six is 6the element at eight is 8the element at nine is 9the element at ten is 10the element at six is 6the element at eight is 8the element at nine is 9the element at ten is 10

(4)排序

-  自然顺序

kotlin为Map集合提供了基本的排序函数 toSortedMap(),该函数按照其自然顺序排序。

val numbers = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)println("Sorted ascending: ${numbers.toSortedMap()}")输出:{four=4, one=1, three=3, two=2}

-  自定义顺序

kotlin为Map集合提供了排序函数 toSortedMap(), 它们接受一个将集合元素映射为 Comparable 值的选择器函数,并以该值的自然顺序对集合进行升序或降序。

var numbers = linkedMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)var numbersSort = numbers.toSortedMap(compareBy { it })//it为key值val numbersSortDescend = numbers.toSortedMap(compareByDescending { it })println(numbers)println(numbersSort)println(numbersSortDescend)输出:{one=1, two=2, three=3, four=4}{four=4, one=1, three=3, two=2}{two=2, three=3, one=1, four=4}

(5)转换

Kotlin 标准库为Map集合转换提供了一组扩展函数, 这些函数根据提供的转换规则从现有集合中构建新集合:

val map = mapOf("six" to 6, "eight" to 8, "nine" to 9, "ten" to 10) //只读println(map)val mapKey = map.mapKeys { it.key.toUpperCase() }val mapValue = map.mapValues { it.value + it.key.length }println(mapKey)println(mapValue)输出:{six=6, eight=8, nine=9, ten=10}{SIX=6, EIGHT=8, NINE=9, TEN=10}{six=9, eight=13, nine=13, ten=13}

(6)过滤

在Kotlin中,过滤条件由条件定义——接受一个集合元素并且返回布尔值的 lambda 表达式:true 说明给定元素与条件匹配,false 则表示不匹配。

val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)println(numbersMap)val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("1") && value > 10}println(filteredMap)val keyMap = numbersMap.filterKeys {        it.contains("key1")}println(keyMap)val valueMap = numbersMap.filterValues {        it >= 3}println(valueMap)输出:{key1=1, key2=2, key3=3, key11=11}{key11=11}{key1=1, key11=11}{key3=3, key11=11}

参考文档:https://www.kotlincn.net/docs/reference/map-operations.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值