给定一个字符串 ,转成想要的List 关键字:filterTo 和 -=
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)
输出结果:
true
false
MutableList 是可以进行写操作的 List ,关键词 shuffle() 大打乱次序
val numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)
numbers.removeAt(1)
numbers[0] = 0
numbers.shuffle()
println(numbers)
输出结果:
[4, 0, 3, 5]
set
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())
输出结果:
false
true
Map 的默认实现 – LinkedHashMap—— 迭代 Map 时保留元素插入的顺序。 反之,另一种实现 – HashMap—— 不声明元素的顺序。
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 (1 in 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
MutableMap 是一个具有写操作的 Map 接口,可以使用该接口添加一个新的键值对或更新给定键的值。
val numbersMap = mutableMapOf("one" to 1, "two" to 2)
numbersMap.put("three", 3)
numbersMap["one"] = 11
println(numbersMap)
输出结果:
{one=11, two=2, three=3}