Map 类型
Key具有唯一性,存入 Entry 时当 Key 重复时会覆盖之前的 Value。to 关键字本身是一个中缀表达式,返回一个 Pair。
创建方式 | 举例 |
mapOf () | val map1 = mapOf( 'A' to 3, 2 to "哈哈", false to true ) //随意类型 val map2 = mapOf<Int,String>( 1 to "你", 2 to "我", 3 to "他") //确定类型 |
mutableMapOf () | |
hashMapOf () linkedMapOf () sortedMapOf () | HashMap,允许null键null值,随着存储Entry顺序会发生变化 LinkedHashMap,使用链表维护顺序,遍历时得到的是先存入的 TreeMap,使用红黑二叉树进行排序 |
emptyMap () | val em = emptyMap<Int, String>() val me = mapOf<Int, String>() em.size=0,em.isEmpty()=true,em.hashCode()=0 空map都是相等的,em==me 为 true |
属性
.entries | 获取 Map 中的所有 Entry,是一个Set Entry.component1(),访问 Key Entry.component2(),访问 Value |
.keys | 获取 Map 中的所有 Key,是一个Set |
.values | 获取 Map 中的所有 Value,是一个Set |
.size | 获取 Map 中的 Entry 数量,是一个Int |
转换
Map.Entry.toPair () :Pair<K,V> | 把 Map 的 Entry 转换为 Pair,是 entry 的方法 |
Map.toMutableMap () | 把只读的 Map 转化为可编辑的 MutableMap |
Iterable<Pair<K,V>>.toMap (Map):Map | Iterable<Pair<K,V>>.toMap (Map):Map 把装有 Pair 的 Iterable 转换为 Map |
增删
put (键,值) | put(K,V):V? 添加 Entry,如果 Key 存在就覆盖 |
plus (二元组/集合/数组/序列) plusAssign (二元组/集合/数组/序列) minus (二元组/集合/数组/序列)????? minusAssign (二元组/集合/数组/序列)???? | plus(Pair<K,V>):Map<K,V> plus(Map<K,V>):Map<K,V> plus(Iterable<Pair<K,V>>):Map<K,V> plus(Array<Pair<K,V>>):Map<K,V> plus(Sequence<Pair<K,V>>):Map<K,V> 加法运算,拼接,推荐使用操作符 + plusAssign,拼接后赋值给原Map,推荐操作符 += 减法同理????? |
获取
get (键) getValue (键) getOrDefault (键,默认值) getOrElse (键,默认值) getOrPut (键,默认值) | get(K):V? 根据 Key 获取对应的 Value,没有则返回null,推荐使用操作符 [ ] |
getValue(K):V 根据 Key 获取对应的 Value,没有则报错 | |
getOrDefault(K,V):V 根据 Key 获取对应的 Value,没有则返回默认值,默认值类型要和原值的类型一样 | |
getOrElse(K,() -> V):V 同上??? | |
getOrPut(K,() -> V):V 根据 Key 获取对应的 Value,没有则添加进 Map 中 |
判断
containsKey (键) containsValue (值) | containsKey(K):Boolean Map中是否包含该 Key,包含true,不含false |
containsValue (V):Boolean Map中是否包含该 Value,包含true,不含false |
运算
mapKeys (function) mapValues (function) | mapKeys(Map.Entry<K,V> -> R):Map<R,V>) 对 Map 中的 Entry 进行运算后,将 Key 赋予新值 |
mapValues(Map.Entry<K,V> -> R):Map<K,R>) 对 Map 中的 Entry 进行运算后,将 Value 赋予新值 |
筛选
filterKeys (predicate) filterValues (predicate) filter (predicate) | filterKeys(K -> Boolean):Map<K,V> 返回一个Map,包含所有 Key 满足条件的 Entry |
filterValues(V -> Boolean):Map<K,V> 返回一个Map,包含所有 Value 满足条件的 Entry | |
filter(Map.Entry<K,V> -> Boolean):Map<K,V> 返回一个Map,包含所有 Entry 满足条件的 Entry |
MutableMap 中的方法
remove (键):值? | remove (K):V? 根据 Key 移除 Entry,返回被移除的 Value,没有对应的 Key 返回 null |
clear () | clear ():Unit 清空 MutableMap 中的 Entry |