1. 声明
HashMap 的 key 与 value 类型可以相同也可以不同,根据定义,不受限制。
注意:无需确定长度,自增长。
HashMap<Integer, String> map = new HashMap<>();
2. 增删改查
HashMap<Integer, String> map = new HashMap<>();
//增
map.put(001, "mary");
map.put(002, "sun");
map.put(003, "lihua");
//改 替换 hashMap 中是指定的key对应的 value
map.replace(001, "hello");
//查
map.get(003);
map.get(1); //没有则返回null
//若map存在该键,返回其对应值,若不存在则返回默认值(自己定义)
map.getOrDefault(004, "刘备")
//删
map.remove(001); //按键名删除
map.clear(); //删除所有键值对
3. map长度
map.size();
4. 查看是否有对应key, value
存在返回true
boolean ansKey = map.containsKey(001);
boolean ansValue = map.containsValue("sun");
5. map是否为空
boolean ans = map.isEmpty();
6. 返回map中所有value
如map = {1=mary, 2=sun, 3=lihua},返回[mary, sun, lihua]数组;map为空,返回[];
map.values();
7. 遍历
1. ForEach循环遍历
Map.entry<> 结合map.entrySet()
HashMap<Integer, String> map = new HashMap<>();
map.put(001, "mary");
map.put(002, "sun");
map.put(003, "lihua");
for (Map.Entry<Integer, String> entry: map.entrySet()) {
System.out.println(entry.getKey() + "--->" + entry.getValue());
}
2. 只遍历键/值
for (Integer key: map.keySet()) {
System.out.println(key);
}
for (String value: map.values()) {
System.out.println(value);
}
3.使用lambda表达式
注意:仅支持jdk8及以上
map.forEach((k, v) -> {
System.out.println(k +"-->"+ v);
});