Frequently used methods: (JDK7)1
2
3
4
5
6
7
8
9
10clear()
containsKey(Object key)
entrySet()
get(Object key)
getOrDefault(key) (JDK8)
isEmpty()
keySet()
put(K key, V value)
putAll(Map<? extends K,? extends V> m)
remove(Object key): remove entry
Entry
Map中采用Entry内部类表示一个映射,每个键值对就是一个Entry
map.entrySet()
得到整个entrySetmap.entrySet().iterator()
得到entrySet的iteratormap.entrySet().iterator().next()
得到每一个具体的Entry
1
2
3
4
5
6
7Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();
while(it.hasNext()) {
Map.Entry<Integer,Integer> entry=it.next();
int key=entry.getKey();
int value=entry.getValue();
System.out.println(key+" "+value);
}
另外有entrySet()
和keySet()
的解释这里不做说明.
不同种类的遍历方式:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "val1");
map.put("2", "val2");
map.put("3", "val3");
System.out.println("1. 通过Map.keySet遍历key和value");
for (String key : map.keySet()) {
System.out.println("key= " + key + ", value= " + map.get(key));
}
System.out.println("2. 通过Map.entrySet的iterator遍历key和value");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("key= " + entry.getKey() + ", value= " + entry.getValue());
}
System.out.println("3. 通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + ", value= " + entry.getValue());
}
System.out.println("4. 通过Map.values遍历所有的values,但是不能遍历key");
for (String v : map.values()) {
System.out.println("value= " + v);
}
}