val list = ArrayList<String>()
list.add("苹果")
list.add("香蕉")
list.add("橘子")
val list = listOf<String>("苹果", "香蕉", "橘子")
fun main() {
val list = listOf<String>("苹果", "香蕉", "橘子")
for (fruit in list) {
println(fruit)
}
}
fun main() {
val list = mutableListOf<String>("苹果", "香蕉", "橘子")
list.add("哈密瓜")
for (fruit in list) {
println(fruit)
}
}
val set = setOf<String>("香蕉", "橘子", "苹果")
val map = HashMap<String, Int>()
map.put("香蕉", 1)
map.put("西瓜", 2)
val map = HashMap<String, Int>()
map["香蕉"] = 1
map["西瓜"] = 2
map.get("香蕉")
//或者还可以是这样(推荐)
map["香蕉"]
fun main() {
val map = mapOf<String, Int>("香蕉" to 1, "西瓜" to 2)
for ((fruit, number) in map) {
println("fruit is " + fruit + "number is " + number)
}
}
写法一:
val list = listOf<String>("Apple", "Banana", "Orange", "Pear")
var maxLengthFruit = ""
for (fruit in list) {
if (fruit.length > maxLengthFruit.length) {
maxLengthFruit = fruit
}
}
println("max length fruit is " + maxLengthFruit)
写法二:(使用函数式API写法)
val list = listOf<String>("Apple", "Banana", "Orange", "Pear")
val maxLengthFruit = list.maxBy { it.length }
println("max length fruit is " + maxLengthFruit)
{参数名1: 参数类型, 参数名2: 参数类型 -> 函数体}
val list = listOf<String>("Apple", "Banana", "Orange", "Pear")
//定义一个lambda表达式
val lambda = {fruit: String -> fruit.length}
//然后将这个lambda表达式作为参数传递给maxBy函数,maxBy函数的作用就是遍历集合,根据参数条件来找到最大值
val maxLengthFruit = list.maxBy(lambda)
val maxLengthFruit = list.maxBy({fruit: String -> fruit.length})
val maxLengthFruit = list.maxBy(){fruit: String -> fruit.length}
val maxLengthFruit = list.maxBy{fruit: String -> fruit.length}
val maxLengthFruit = list.maxBy{fruit -> fruit.length}
val maxLenght = list.maxBy{it.length}
val list = listOf<String>("Apple", "Banana")
val newList = list.map { it.toUpperCase() }
for (fruit in newList) {
println(fruit)
}
val list = listOf<String>("Apple", "Banana", "Orange", "Pear", "Grape")
val newList = list.filter { it.length <= 5 }
.map { it.toUpperCase() }
for (fruit in newList) {
println(fruit)
}
val list = listOf<String>("Apple", "Banana", "Orange", "Pear", "Grape")
val anyResult = list.any {it.length <= 5}
val allResult = list.all { it.length <= 5 }
println("anyResult is" + anyResult + ", allResult is" + allResult)