Map使用键值对来存储数据。Map是一个接口,定义了对数据的增删改查,替换和比较等等基本的操作。
Map内部定义了一个内部接口Entry,可以通过Map的 Set<Map.Entry<K, V>> entrySet()来获取Entry对象。
Map怎么判断键值(key)是否存在呢?看看源码的实现
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;
}
这个方法是jdk1.8引入的,用来判断Map中是否存在给定key值。
Map的获取key的方法和获取value的方法没有具体实现,由子类去实现
V get(Object key);
V put(K key, V value);
下面列出Map中没有具体实现的方法
int size();//获取集合长度
boolean isEmpty();//判断集合是否为空
boolean containsValue(Object value);//判断集合是否含有给定值
V remove(Object key);//删除集合给定值
void putAll(Map<? extends K, ? extends V> m);//添加一个集合元素
void clear();//清空集合
Set<K> keySet();
Collection<V> values();//获取集合全部值
boolean equals(Object o);
int hashCode();
实际上,Map里面的数据是由内部接口Entry来维护的,即所有数据都是经过Entry来保存,看看Map里面接口实现
interface Entry<K,V> {
V getValue();
V setValue(V value);
boolean equals(Object o);
int hashCode();
public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getKey().compareTo(c2.getKey());
}
public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getValue().compareTo(c2.getValue());
}
public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
}
public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
}
}
Entry可以设置键值和获取键值。