基礎的排序
數字會依照升序排列
fun main (){
val numbers = mutableListOf(4,1,3,2)
numbers.sort()
println("Sort into ascending: $numbers")
// result
// Sort into ascending: [1, 2, 3, 4]
}
單字會依照第一個字母在字母表的順序做升序排列
fun main (){
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sort()
println("Sort into ascending: $numbers")
// result
// Sort into ascending: [four, one, three, two]
}
sort 是升序 而 sortDescending 是降序
數字會依照降序排列
fun main (){
val numbers = mutableListOf(4,1,3,2)
numbers.sortDescending()
println("Sort into descending: $numbers")
// result
//Sort into descending: [4, 3, 2, 1]
}
單字會依照第一個字母在字母表的順序做降序排列
fun main (){
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sortDescending()
println("Sort into descending: $numbers")
// result
// Sort into descending: [two, three, one, four]
}
下面依照 String 字數 做升序排列
fun main (){
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sortBy { it.length }
println("Sort into ascending by length: $numbers")
}
// result:
// Sort into ascending by length: [one, two, four, three]
下面依照單字最後一個字母在字母表的順序做降序排列
fun main (){
val numbers = mutableListOf("one", "two", "three", "four")
numbers.sortByDescending { it.last() }
println("Sort into descending by the last letter: $numbers")
}
// result:
// Sort into descending by the last letter: [four, two, one, three]
forEach 用於進行遍歷每個元素 。
fun main (){
val numbers = mutableListOf<Int>(1,2,3,4,5)
numbers.forEach{ println(it * 2) }
// result:
// 2
// 4
// 6
// 8
// 10
}
過濾所有符合條件的元素,形成一個新的集合
it 代表 List 中的單一元素, it 可以換作 其它 的名稱
fun main (){
val numbers = mutableListOf<Int>(1,2,3,4,5)
val filterList = numbers.filter{ it > 2}
println(filterList)
}
// result
//[3, 4, 5]