4.4 Map接口
Map是将键映射到值的对象。Map不能包含重复键,每个键最多可映射一个值。
Map接口包括基本操作的方法(如put、get、remove、containsKey、containsValue、size和empty)、批量操作(如putAll和clear)和集合视图(如keySet、entrySet和values)。
Java平台包含3个通用的Map实现:HashMap、TreeMap和LinkedHashMap。它们的行为和性能完全类似于HashSet、TreeSet和LinkedHashSet。
4.4.1 Map接口基本操作
Map基本操作的方法(如put、get、remove、containsKey、containsValue、size和empty)与Hashtable中的对应操作完全相同。以下程序用于统计单词出现的次数:

4.4.2 Map接口批量操作
putAll操作是Collection接口的addAll操作的Map模拟。除了将一个Map转储到另一个Map之外,它还有第二个用途,提供一种使用默认值实现属性映射创建的简洁方法。下面演示第二个用途的静态工厂方法:

4.4.3 Map集合视图
Collection视图方法允许以下3种方式将Map视为Collection:
· keySet:Map中包含的键集。
· values:Map中包含的值集合。此Collection不是Set,因为多个键可以映射到相同的值。
· entrySet:Map中包含的键值对集合。Map接口提供了一个名为Map.Entry的小型嵌套接口。
Collection视图提供迭代Map的唯一方法。此示例使用for-each来迭代Map中的键:

以下示例使用迭代器来过滤数据:

以下示例将Map的键和值都迭代输出:

Collection视图还支持多种形式来删除元素,包括remove、removeAll、retainAll、clear和Iterator.remove操作。
需要注意的是,Collection视图在任何情况下都不支持元素添加。