Java 集合 --- 如何遍历Map
- Map的基本操作
- 如何遍历Map
- Type of HashMap
- Map没有继承Collection接口
- AbstractMap和AbstractCollection是平级关系
Map的基本操作
package map;
import java.util.*;
/**
* This program demonstrates the use of a map with key type String and value type Employee.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class MapTest {
public static void main(String[] args) {
Map<String, Employee> staff = new HashMap<>();
staff.put("144-25-5464", new Employee("Amy Lee"));
staff.put("567-24-2546", new Employee("Harry Hacker"));
staff.put("157-62-7935", new Employee("Gary Cooper"));
staff.put("456-62-5527", new Employee("Francesca Cruz"));
// print all entries
System.out.println(staff);
// remove an entry
staff.remove("567-24-2546");
// replace an entry
staff.put("456-62-5527", new Employee("Francesca Miller"));
// look up a value
System.out.println(staff.get("157-62-7935"));
// iterate through all entries
staff.forEach((k, v) ->
System.out.println("key=" + k + ", value=" + v));
}
}
如何遍历Map
the set of keys: 将所有的key作为一个set返回
Set<K> keySet()
Set<String> keys = map.keySet();
for (String key : keys) {
do something with key
}
the collection of values (which is not a set): 将所有的value作为一个collection返回
Collection<V> values()
Map<String,String> map=new HashMap<>();
map.put("abc","123");
map.put("efg","456");
// 使用增强型for遍历循环Map集合
Collection<String> values = map.values();
for (String value : values) {
System.out.println(value);
}
the set of key/value pairs: 得到每一对key value pair
Set<Map.Entry<K, V>> entrySet()
for (Map.Entry<String, Employee> entry : staff.entrySet()) {
String k = entry.getKey();
Employee v = entry.getValue();
do something with k, v
}
Type of HashMap
HashMap
- Hash table based implementation of the Map interface
- the default load factor (.75)
- 有一个子类为LinkedHashMap, 元素按照加入顺序排序
TreeMap
- A Red-Black tree based NavigableMap implementation.
- 需要根据compareTo排序
EumerateHashMap
- A specialized Map implementation for use with enum type keys.
- All of the keys in an enum map must come from a single enum type that is specified
WeakHashMap
- Hash table based implementation of the Map interface, with weak keys.
- An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use