fun main(args: Array<String>){
val words ="A long time ago in a galaxy far far away".split(" ")
val shortWords = mutableListOf<String>()
words.getShortWordsTo(shortWords, 3)
println(shortWords)}
fun List<String>.getShortWordsTo(shortWords: MutableList<String>, maxLength: Int){
this.filterTo(shortWords){ it.length <= maxLength }
val articles = setOf("a", "A", "an", "An", "the", "The")
shortWords -= articles
}
输出结果:[ago, in, far, far]
衍生:
***+=*** 输出结果:[A, ago, in, a, far, far, a, A, an, An, the, The]
***==*** 输出结果:[A, ago, in, a, far, far]
List 元素怎么才算相等
val bob = Person("Bob", 31)
val people = listOf(Person("Adam", 20), bob, bob)
val people2 = listOf(Person("Adam", 20), Person("Bob", 31), bob)
println(people == people2)
bob.age =32
println(people == people2)
val numbers = setOf(1, 2, 3, 4)
println("Number of elements: ${numbers.size}")if(numbers.contains(1)) println("1 is in the set")
val numbersBackwards = setOf(4, 3, 2, 1)
println("The sets are equal: ${numbers == numbersBackwards}")
输出结果:
Number of elements: 4
1 is in the set
The sets are equal: true
Set的默认实现 - LinkedHashSet—— 保留元素插入的顺序
val numbers = setOf(1, 2, 3, 4) // LinkedHashSet is the default implementation
val numbersBackwards = setOf(4, 3, 2, 1)
println(numbers.first()== numbersBackwards.first())
println(numbers.first()== numbersBackwards.last())
val numbersMap = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key4" to 1)
println("All keys: ${numbersMap.keys}")
println("All values: ${numbersMap.values}")if("key2"in numbersMap) println("Value by key \"key2\": ${numbersMap["key2"]}")if(1in numbersMap.values) println("The value 1 is in the map")if(numbersMap.containsValue(1)) println("The value 1 is in the map") // 同上
输出结果:
All keys: [key1, key2, key3, key4]
All values: [1, 2, 3, 1]
Value by key "key2": 2
The value 1 is in the map
The value 1 is in the map