第10章 List 與 Set
List
var list:List<String> = listOf("A", "B", "C")
//簡化
var list = listOf<String>("A", "B", "C")
//簡化
var list = listOf("A", "B", "C")
//可以放重覆的
var list = listOf("A", "B", "C", "C")
取得元素
val list = listOf("A", "B", "C")
println(list[0]) // A
println(list[1]) // B
println(list[2]) // C
println(list.first()) // A
println(list.last()) // C
getOrElse
val list = listOf("A", "B", "C")
println(list.getOrElse(3) {""}) //取不到回傳空白
val list = listOf("A", "B", "C")
println(list.getOrNull(3)) //null
getOrNull
Contains
val list = listOf("A", "B", "C")
println(list.contains("A")) //true
println(list.containsAll(listOf("A", "B"))) //true
修改內容
val list = mutableListOf("A", "B", "C")
list[0] = "D"
println(list) // [D, B, C]
List => 不可修改
MutableList => 可修改
add
val list = mutableListOf("A", "B", "C")
list.add("D")
println(list)
// [A, B, C, D]
val list = mutableListOf("A", "B", "C")
list.add(1, "D")
println(list)
//[A, D, B, C]
Remove
val list = mutableListOf("A", "B", "C")
list.remove("A")
println(list)
// [B, C]
list.remove("D") //Fine
val list = mutableListOf("A", "B", "C")
list.removeAt(0)
println(list)
// [B, C]
ForEach
val list = listOf("A", "B", "C")
list.forEach {
print(it)
}
//ABC
ForEachIndex
val list = mutableListOf("A", "B", "C")
list.forEachIndexed { index, s ->
println("$index, $s")
}
0, A
1, B
2, C
解構
val (s1, s2, s3) = listOf("1", "2", "3")
Set
val set = setOf("A", "B", "C")
Set 裡面的內容不可重覆
val set = mutableSetOf("A", "B", "C")
Set
val set = setOf("A", "B", "C", "A")
println(set) //[A, B, C]
val set = setOf("A", "B", "C")
println(set.contains("A")) //true
val set = setOf("A", "B", "C")
println(set.elementAt(0)) //A
Operation
val numbers = listOf("one", "two", "three", "four")
val result = numbers.filter { it.length > 3 }
println(result) //[three, four]
Operation
var list = listOf(1, 2, 3)
println(list.map { it * 2 }) // [2, 4, 6]
val colors = listOf("red", "brown", "grey")
val animals = listOf("fox", "bear", "wolf")
val list: List<Pair<String, String>> = colors zip animals
println(list)
//[(red, fox), (brown, bear), (grey, wolf)]
val numbers = listOf("one", "two", "three", "four")
val sortedNumbers = numbers.sortedBy { it.length }
println(sortedNumbers)
//[one, two, four, three]
挑戰練習 美化酒水單
*** Welcome to Taernyl's Folly ***
Dragon's Breath...............5.91
Shirley's Temple..............4.12
Goblet of LaCroix.............1.22
Pickled camel hump............7.33
Iced boilermaker.............11.22
挑戰練習 進一步美化酒水單
*** Welcome to Taernyl's Folly ***
~[shandy]~
Dragon's Breath...............5.91
~[elixir]~
Shirley's Temple..............4.12
Iced boilermaker.............11.22
~[meal]~
Goblet of LaCroix.............1.22
~[desert dessert]~
Pickled camel hump............7.33
List & Set
By evanchen76
List & Set
- 340