介绍
Map是一个key到value的映射接口,即map集合存储的是键值对,一个map不能包含重复的key,每个key至多只能映射一个值。Map接口中键和值一一映射. 可以通过键来获取值和设定值。
类图
Map的遍历
// 按照key的字典顺序来排序(升序)
Map<String, BigDecimal> map = new TreeMap<>();
for (Map.Entry entry : map.entrySet()) {
// 遍历map
TrendDTO dto = new TrendDTO(entry.getKey(),entry.getValue());
newList.add(dto);
}
源码
参照JDK1.8版本
查询操作
//返回map的大小
int size();
//map为空,返回true
boolean isEmpty();
//如果map包含指定key,则返回true
boolean containsKey(Object key);
//如果map中有一个或多个key对应的值是指定的value,则返回true
boolean containsValue(Object value);
//按key获取map的指定值
V get(Object key);
修改操作
//按key-value向map中放值
V put(K key, V value);
//删除map中指定的key及对应的value
V remove(Object key);
批量操作
/**
* Copies all of the mappings from the specified map to this map
* (optional operation).
*/
void putAll(Map<? extends K, ? extends V> m);
/**
* Removes all of the mappings from this map (optional
* operation).
* The map will be empty after this call returns.
*/
void clear();
比较和散列
//Compares the specified object with this map for equality.
boolean equals(Object o);
//Returns the hash code value for this map.
int hashCode();