Map接口存储的是一对对的映射 从key到value的映射 key是唯一的,value可以重复
- Map接口常用方法
put(Object key,Object value) 以键-值 方式存储
get(Object key) 返回相关联的值 如果该键不存在 返回null
remove(Object key) 删除指定的键值对
size() 返回集合元素个数
keySet() 返回键的集合
values() 返回值得集合
containsKey(Object key) 判断是否存在相应的键值对
Map实例
public class Countries {
public static void main(String[] args) {
//创建集合对象
Map countries = new HashMap();
countries.put("China","中国");
countries.put("USA","美国");
countries.put("Japan","日本");
countries.put("India","印度");
//查看集合中元素个数
System.out.println("集合中元素个数是" + countries.size());
//获取集合中特定的key值所对应的value 如果找不到对应值 返回null
System.out.println(countries.get("USA"));
//判断集合中是否存在某一个国家
System.out.println("是否存在键值为China的国家" + "\t" + countries.containsKey("China"));
//删除特定的键值对
countries.remove("USA");
System.out.println("是否存在键值为USA的国家" + "\t" + countries.containsKey("USA"));
System.out.println("集合中元素个数是" + countries.size());
//获取键的集合 获取值的集合 获取键值对的集合
System.out.println(countries.keySet());
System.out.println(countries.values());
System.out.println(countries);
}
}
结果
- 遍历Map
1、通过迭代器Iterator实现
public class Countries {
public static void main(String[] args) {
//创建集合对象
Map countries = new HashMap();
countries.put("China","中国");
countries.put("USA","美国");
countries.put("Japan","日本");
countries.put("India","印度");
Set keys = countries.keySet(); //获取Map中所有key
//用迭代器Iterator遍历key集合
Iterator a = keys.iterator();
while (a.hasNext()){
String key = (String)a.next();
String value = (String) countries.get(key);//根据Map中每个key去获取对应的value
System.out.println(key + "----->" + value);
}
}
}
2、通过增强for循环实现
public class Countries {
public static void main(String[] args) {
//创建集合对象
Map countries = new HashMap();
countries.put("China","中国");
countries.put("USA","美国");
countries.put("Japan","日本");
countries.put("India","印度");
//遍历Map 通过遍历key 去遍历value
Set keys = countries.keySet(); //获取Map中所有key
for (Object obj : keys) {
String key = (String) obj;
String value = (String) countries.get(key);//根据Map中每个key去获取对应的value
System.out.println(key + "----->" + value);
}
}
}