零基础学习Java之Map集合
概述
上一个文章说到非常常用的Set集合。从文章中我们知道Set集合有序的单列集合,它固然可以解决生活中很多的问题,但是在我们集合中的元素并不都是孤立存在的单个元素,有一些会存在一定的对应关系(映射关系),比如在学校里,我们的的学号和学生的对应关系等。所以呢,Java又专门设计了Map接口,通过这个接口实现的集合类的元素是有对应关系(映射关系)的元素,它们又被称为键值对,通过对应的键可以找到对应的值。
Map接口的特点:
- 元素是成对存在的,它们又被称为键值对(key和value),通过键可以找对所对应的值;(又被称为双列集合)
- 集合中的元素是无序;
- Map中的集合键不能重复,但是值是可以重复的;每个键可以映射至多一个值;
- Map中的集合的值可以是单个值,也可以是数组或集合;
Map的使用
常用方法介绍
不同于Set这类的单列集合,Map作为双列集合,其方法自然有很多与单列集合是不一样的。下面对Map中常用的方法进行介绍:
- boolean isEmpty(): 判断集合是否为空,返回true表示空集合;
- boolean containsKey(Object key):判断集合中是否存在指定的key值
- boolean containsValue(Object value):判断集合中是否存在指定的value值,返回 true表示存在指定的值的一个或多个键;
- V get(Object key):返回指定的键映射的值,如果这个Map不包含的键映射返回null;
- V put(K key, V value):添加key及其映射,如果key已经存在,则替换为新的映射(新的value);
- void putAll(Map<? extends K,? extends V> m):将一个新的Map集合直接添加到Map集合中;
- -V remove(Object key):删除集合中指定key值的映射;
- void clear():移除集合中所有的映射;
- Set keySet():返回一个该集合中key值的Set的集合视图;
- Collection values():返回一个该集合总value值的集合视图;
- Set<Map.Entry<K,V>> entrySet():返回集合中包含的映射的一个集合视图 ;
- int size():返回集合的大小
Map集合的遍历
不同于Set这类单列集合,Map的遍历并不支持foreach,这是因为其没有继承java.lang.Iterable接口,也没有实现Iterator iterator()方法。所以它只能采取下面的方式来进行元素的遍历:
- 单独遍历key值和value值
- 通过Map.Entry(Map的接口)的实现类来遍历映射关系;
代码示例
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapDemo {
public static void main(String[] args) {
//创建hashmap集合
Map<String,String> hashMap1 = new HashMap<>();
Map<String,String> hashMap2 = new HashMap<>();
//添加元素 put(K key,V value)
hashMap1.put("张三","jack");
hashMap1.put("李四","marry");
hashMap2.put("王五","lucy");
hashMap2.put("赵六","bob");
System.out.println(hashMap1);
System.out.println(hashMap2);
//添加元素 putAll(Map<? extends K,? extends V> m)
hashMap1.putAll(hashMap2);
System.out.println(hashMap1);
//删除元素 remove(Object key) remove(Object key, Object value)
hashMap1.remove("王五");
hashMap1.remove("王五","lucy");
System.out.println(hashMap1);
//删除元素 void clear()
hashMap2.clear();
//元素查询的操作 get(Object key)
String get = hashMap1.get("赵六");
System.out.println(get);
//元素查询的操作 containsKey(Object key)
boolean containsKey = hashMap1.containsKey("王五");
System.out.println(containsKey);
//元素查询的操作 containsValue(Object value)
boolean containsValue = hashMap1.containsValue("jack");
System.out.println(containsValue);
//元素查询的操作
boolean empty = hashMap2.isEmpty();
System.out.println(empty);
//元视图操作的方法 keySet()
Set<String> keySet = hashMap1.keySet();
System.out.println(keySet);
//遍历key
for(String key : keySet){
System.out.println(key);
}
//元视图操作的方法 values()
Collection<String> values = hashMap1.values();
System.out.println(values);
//遍历value
for(String value : values){
System.out.println(value);
}
//元视图操作的方法 entrySet()
Set<Map.Entry<String, String>> entries = hashMap1.entrySet();
System.out.println(entries);
//成对遍历
for(Map.Entry<String, String> entry : entries){
System.out.println(entry);
}
//集合大小 size()
int size = hashMap1.size();
System.out.println(size);
}
}
Map的实现类
Map接口也有很多的实现类,但是下面我们只介绍常用的实现类,比如:HashMap、TreeMap、LinkedHashMap和Properties。下面对他们分别进行介绍。
HashMap
HashMap是哈希表(散列表),HashMap 实现了 Map 接口,根据键的 HashCode 值存储数据,具有很快的访问速度,最多允许一条记录的键为 null,不支持线程同步(线程不安全的)。
HashMap的源码如下:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
... //省略了一部分代码
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 ,初始化容量
static final int MAXIMUM_CAPACITY = 1 << 30;//最大容量
static final float DEFAULT_LOAD_FACTOR = 0.75f;//默认容量负载
// 当添加元素使得对应链表长度达到8时将链表转换为红黑树
static final int TREEIFY_THRESHOLD = 8;
//删除元素使得对应链表长度小于6时将链表转换为链表
static final int UNTREEIFY_THRESHOLD = 6;
//最小树的容量
static final int MIN_TREEIFY_CAPACITY = 64;
//存储元素的数组
transient Node<K,V>[] table;
//缓存entrySet().
transient Set<Map.Entry<K,V>> entrySet;
//版本迭代的次数
transient int modCount;
//临界值(用来判断是否进行扩容用的)
int threshold;
//填充比
final float loadFactor;
/*
HashMap的扩容机制
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold; //旧表长度为临界值
int newCap, newThr = 0;
//如果旧表的长度不是空
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//把新表的长度设置为旧表长度的两倍,newCap=2*oldCap
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
//把新表设置为旧表的两倍
newThr = oldThr << 1; // newThr=oldThr*2
}
//如果旧表的长度的是0,就是说第一次初始化表
else if (oldThr > 0) // 初始容量设置为阈值
newCap = oldThr;
else { // 零初始阈值表示使用默认值
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;//新表长度乘以负载因子
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
//然后构造新表,初始化表中的数据
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;//把新表赋值给table
if (oldTab != null) {//原表不是空要把原表中数据移动到新表中
//遍历原来的旧表
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)//说明这个node没有链表直接放在新表的e.hash & (newCap - 1)位置
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//如果e后边有链表,到这里表示e后面带着个单链表,需要遍历单链表,将每个结点重
else { // preserve order保证顺序新计算在新表的位置,并进行搬运
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;//记录下一个结点
//新表是旧表的两倍容量,实例上就把单链表拆分为两队,
//e.hash&oldCap为偶数一队,e.hash&oldCap为奇数一对
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {//lo队不为null,放在新表原位置
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {//hi队不为null,放在新表j+oldCap位置
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab; //返回新表
}
/*
HashMap的常用方法的源码
*/
//get方法
public V get(Object key) {
Node<K,V> e;
//调用了getNode,使用三元运算符比较
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//containsKey
public boolean containsKey(Object key) {
//调用了getNode
return getNode(hash(key), key) != null;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // 始终检查第一个节点
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
//put方法
public V put(K key, V value) {
//调用了putVal方法
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//remove方法
public V remove(Object key) {
Node<K,V> e;
//调用了removeNode方法
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next;
else
p.next = node.next;
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
//clear
public void clear() {
Node<K,V>[] tab;
modCount++;
if ((tab = table) != null && size > 0) {
size = 0;
for (int i = 0; i < tab.length; ++i)
tab[i] = null;
}
}
//containsValue
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
从上面的源码中我们可以看到:
- hash表默认大小为16(即Node数组大小16),如果Node[]数组中的元素达到阈值,重新调整HashMap大小使其变为原来的2倍
- 然后是HashMap的一些常见的方法的源码介绍
TreeMap
TreeMap基于红黑树(Red-Black tree) 实现的。该映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,其具体取决于使用的构造方法。
相对于源码,TreeMap的排序更值得我们关注,下面对其排序举例子说明
import org.junit.Test;
import java.util.Comparator;
import java.util.Map;
import java.util.Set;
public class TreeMap {
@Test
public void test1(){
//创建集合
Map<String, Integer> treemap = new java.util.TreeMap<>();
//添加元素
treemap.put("Jack", 11000);
treemap.put("Alice", 12000);
treemap.put("Lucy", 15000);
treemap.put("bob", 14000);
treemap.put("Bo", 14000);
//String实现了Comparable接口,默认按照Unicode编码值排序
Set<Map.Entry<String, Integer>> entrySet = treemap.entrySet();
for (Map.Entry<String, Integer> entry : entrySet) {
System.out.println(entry);
}
}
@Test
public void test2(){
//指定定制比较器Comparator,按照Unicode编码值排序,但是忽略大小写
Map<String, Integer> treemap = new java.util.TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
//添加元素
treemap.put("Jack", 11000);
treemap.put("Alice", 12000);
treemap.put("Lucy", 15000);
treemap.put("bob", 14000);
treemap.put("Bo", 14000);
//String实现了Comparable接口,忽略Unicode编码值的大小写排序
Set<Map.Entry<String, Integer>> entrySet = treemap.entrySet();
for (Map.Entry<String, Integer> entry : entrySet) {
System.out.println(entry);
}
}
}
LinkedHashMap
LinkedHashMap 是 HashMap 的子类。与 HashMap 不同的是,LinkedHashMap 是有序的,这解决了HashMap 无序这一缺点造成的诸多不便。其顺序通常就是将键插入到映射中的顺序(也可以是访问顺序)。
相对于源码,LinkedHashMap的元素顺序更值得我们关注,这里对其顺序举例说明:
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class LinkedMapDemo {
public static void main(String[] args) {
//创建hashmap集合
Map<String,String> linkedHashMap = new LinkedHashMap<>();
//添加元素
linkedHashMap.put("张三","jack");
linkedHashMap.put("李四","marry");
//key相同,新的value会覆盖原来的value
//因为String重写了hashCode和equals方法
linkedHashMap.put("李四","marry11");
//HashMap支持key和value为null值
linkedHashMap.put("王五",null);
linkedHashMap.put(null, "lucy");
//输出结果
Set<Map.Entry<String, String>> entries = linkedHashMap.entrySet();
for (Map.Entry<String,String> entry : entries){
System.out.println(entry);
}
}
}
Properties
Properties 类是 Hashtable 的子类,Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。该类主要用于读取Java的配置文件,不同的编程语言有自己所支持的配置文件,配置文件中很多变量是经常改变的,为了方便用户的配置,能让用户够脱离程序本身去修改相关的变量设置。就像在Java中,其配置文件常为.properties文件,是以键值对的形式进行参数配置的。