Map<K, V>
8 methods一个包含键值对的集合。Map 是只读的;MutableMap 支持修改。
List.size: Int返回此映射中键值对的数量。
Returns
Int
Example
kotlin
val list = listOf(1, 2, 3)
println(list.size) // 3MutableList.add(element: E): Boolean如果映射包含指定的键,则返回 true。
Parameters
| Name | Type | Description |
|---|---|---|
| key | E | 要检查的键。 |
Returns
Boolean
Example
kotlin
val list = mutableListOf(1, 2)
list.add(3)
// list == [1, 2, 3]MutableList.remove(element: E): Boolean如果映射将一个或多个键映射到指定的值,则返回 true。
Parameters
| Name | Type | Description |
|---|---|---|
| value | E | 要检查的值。 |
Returns
Boolean
Example
kotlin
val list = mutableListOf(1, 2, 3)
val ok = list.remove(2)
// ok == true, list == [1, 3]List.contains(element: E): Boolean返回与给定键对应的值,如果不存在则返回 null。
Parameters
| Name | Type | Description |
|---|---|---|
| key | E | 要查找的键。 |
Returns
Boolean
Example
kotlin
val list = listOf(1, 2, 3)
println(list.contains(2)) // true
println(list.contains(9)) // falseList.map { it -> R }: List<R>将指定值与指定键关联。返回之前的值(或 null)。
Parameters
| Name | Type | Description |
|---|---|---|
| key | (E) -> R | 要设置的键。 |
Returns
List<R>
Example
kotlin
val nums = listOf(1, 2, 3)
val squares = nums.map { it * it }
// squares == [1, 4, 9]List.filter { it -> Boolean }: List<E>移除指定的键及其对应的值。返回被移除的值(或 null)。
Parameters
| Name | Type | Description |
|---|---|---|
| key | (E) -> Boolean | 要移除的键。 |
Returns
List<E>
Example
kotlin
val nums = listOf(1, 2, 3, 4)
val evens = nums.filter { it % 2 == 0 }
// evens == [2, 4]List.sorted(): List<E>对映射中的每个条目执行给定的操作。
Returns
List<E>
Example
kotlin
val nums = listOf(3, 1, 2)
val sorted = nums.sorted()
// sorted == [1, 2, 3]
val desc = nums.sortedDescending()
// desc == [3, 2, 1]List.forEach { it -> Unit }返回此映射中所有键的只读 Set。
Parameters
| Name | Type | Description |
|---|---|---|
| action | (E) -> Unit | Action lambda. |
Returns
Unit
Example
kotlin
listOf(1, 2, 3).forEach { println(it) }
// prints:
// 1
// 2
// 3