1、map的常用API
map是双列集合的顶层接口,是所有的双列集合都可以继承使用
2、使用Map集合
//1.创建Map集合的对象
Map<String, String> m = new HashMap<>();
//2.添加元素
//put方法的细节:
//添加/覆盖
//在添加数据时,如果键不存在,会把键值对对象添加到map集合当中,方法返回null
//在添加数据时,如果键是存在的,会把原有的键值对对象覆盖,会把覆盖的值进行返回。
m.put("黄毛小子在此", "张三");
m.put("宝剑锋从磨砺出","司马迁");
m.put("梅花香自苦寒来","哪吒");
//根据键删除值,会把所删除的值返回
String yellow = m.remove("黄毛小子在此");
System.out.println(yellow);//张三
m.clear();//将数据清空
System.out.println(m);//{}
//查询集合中是否有对应的键
boolean yellow1 = m.containsKey("黄毛小子在此");
System.out.println(yellow1);
//查询集合中是否有对应的值
boolean name = m.containsValue("司马迁");
System.out.println(name);
//判断集合是否为空
boolean result = m.isEmpty();
System.out.println(result);
//返回集合的长度,也就是有几个键值对
int size = m.size();
System.out.println(size);
3、Map集合遍历方式
方式一:键找值
//通过keyset()方法将容器变为一个单列set集合
Set<String> keys = map.keySet();
//遍历单列集合,得到每一个键
for (String key : keys) {
//System.out.println(key);
//3.3 利用map集合中的键获取对应的值 get
String value = map.get(key);
System.out.println(key + " = " + value);
}
方式二:键值对
//通过entrySet()方法获取所有的键值对对象,返回一个Set集合
Set<Map.Entry<String, String>> entries = m.entrySet();
//遍历entries这个集合,去得到里面的每一个键值对对象
for (Map.Entry<String, String> entry : entries) {
//使用entry调用get方法获取键和值
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + "=" + value);
}
方式三:lambda表达式
m.forEach((key, value)-> System.out.println(key + "=" + value));