Kotlin学习笔记 第三篇以及实践小demo

2021-05-10  本文已影响0人  光sail
集合list
val list = listOf("Apple", "Banana", "Orange", "Pear", "Grape")for (fruit in list) {
    println(fruit)
}
val set = setOf("Apple", "Banana", "Orange", "Pear", "Grape")for (fruit in set) {
    println(fruit)
}

println("==========================")
val mutableSet = mutableSetOf("Apple", "Banana", "Orange", "Pear", "Grape")
mutableSet.add("Watermelon")for (fruit in mutableSet) {
    println(fruit)
}
集合Map
val map = HashMap<String, Int>()
map.put("Apple", 1)
map.put("Banana", 2)
map.put("Orange", 3)
map.put("Pear", 4)
map.put("Grape", 5)
map["Apple"] = 1
val number = map["Apple"]//从 Map 中读取一条数据
//因此可以将代码优化为一下形式
val map = HashMap<String, Int>()
map["Apple"] = 1
map["Banana"] = 2
map["Orange"] = 3
map["Pear"] = 4
map["Grape"] = 5
val map = mapOf("Apple" to 1, "Banana" to 2, "Orange" to 3, "Pear" to 4, "Grape" to 5)
 
集合的函数式 API
val list = mutableListOf("Apple", "Banana", "Orange", "Pear", "Grape")
var maxLengthFruit = "";for (fruit in list) {
    if (fruit.length > maxLengthFruit.length) {
        maxLengthFruit = fruit
    }
}
println("max length fruit is " + maxLengthFruit)

使用集合 API 实现(集合内数据类型必须一致):

val list = mutableListOf("Apple", "Banana", "Orange", "Pear", "Grape")
val maxLengthFruit = list.maxBy { it.length }
println("max length fruit is " + maxLengthFruit)

学习了一些kotlin这些接触,有了些kotlin使用语感,顺手写个kotlin 语言自定义的柱状图实际体验下,下面链接为demo在github的地址
kotlin 语言自定义的柱状图

上一篇 下一篇

猜你喜欢

热点阅读