val list = listOf(1 ,2 ,3, 4, 5) //创建不可变list
val mutableList = mutableListOf("s","b") //创建可变MutbaleList
val set = setOf(1, 2, 3, 4, 5)//创建不可变Set
val mutableSet = mutableSetOf("haha","wotainanle")//创建可变MutableSet
val map = mapOf(1 to "a",2 to "b", 3 to "c")//创建不可变Map
val mutableMap = mutableMapOf(1 to "l", 2 to "bw", 3 to "nb")//创建可变mutalemap
//空集合
val emptyList: List<Int> = listOf()
val emptySet: Set<Int> = setOf()
val emptyMap: Map<Int, String> = mapOf()
fun main(args: Array<String>) {
//遍历list集合
list.forEach{
println(it)
}
//遍历set集合
set.forEach{
println(it)
}
//遍历mutablemap集合
mutableMap.forEach{
println("K=${it.key},V = ${it.value}")
}
//遍历list的索引+值
list.forEachIndexed { index, value ->
println("list index = ${index} , value =${value}")
}
//遍历set的索引和值
set.forEachIndexed { index, value ->
println("set index = ${index} , value = ${value}")
}
//遍历map集合
map.entries.forEach({ println("key = " + it.key + " value = " + it.value)})
}
输出
1
2
3
4
5
1
2
3
4
5
K=1,V = l
K=2,V = bw
K=3,V = nb
list index = 0 , value =1
list index = 1 , value =2
list index = 2 , value =3
list index = 3 , value =4
list index = 4 , value =5
set index = 0 , value = 1
set index = 1 , value = 2
set index = 2 , value = 3
set index = 3 , value = 4
set index = 4 , value = 5
key = 1 value = a
key = 2 value = b
key = 3 value = c
映射函数,过滤函数,排序函数在集合中运用
val list3 = listOf(5 ,4 ,3 ,2 ,1 ,1)
val list2 = listOf(1, 2, 3, 4, 5)
val set2 = setOf(1, 2, 3, 4, 5)
val map2 = mapOf(1 to "a", 2 to "b", 3 to "c")
//创建数据类Students
data class Students(var id:Int,var name: String,var age:Int,var score:Int){
override fun toString(): String {
return "Students(id=$id ,name='$name',age=$age,score=$score)"
}
}
//添加students对象进集合
var studentList = listOf(
Students(1,"lbw",18,55),
Students(2,"lbf",88,55),
Students(3,"lbfnb",28,55)
)
fun main(args: Array<String>) {
//映射函数运用
println(list2.map { it*it })
println(set2.map { it + 1 })
println(map2.map { it.key + 1 })
//过滤函数运用
println(studentList.filter { it.age > 18 })
println(studentList.filter { it.id == 3 })
println(list2.filterIndexed { index,it -> index > 2 && it > 4})
//排序函数运用
println(list2.reversed())
println(set2.reversed())
println(list3.sorted())
println(list3.distinct())
}
输出结果:
[1, 4, 9, 16, 25]
[2, 3, 4, 5, 6]
[2, 3, 4]
[Students(id=2 ,name='lbf',age=88,score=55), Students(id=3 ,name='lbfnb',age=28,score=55)]
[Students(id=3 ,name='lbfnb',age=28,score=55)]
[5]
[5, 4, 3, 2, 1]
[5, 4, 3, 2, 1]
[1, 1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]