Java HashMap 集合
HashMap
继承自 AbstractMap
以键值对形式存储元素
键不可重复,值可以重复
根据哈希算法和equals方法的比较,保证键不重复
HashMap 是线程不安全的
从JDK 1.2 开始
使用方法
添加元素
示例
HashMap<String, Integer> hm = new HashMap<>(); // 添加指定的键值对元素到集合中 hm.put("电冰箱", 1000); hm.put("洗衣机", 900); hm.put("电视机", 1000); hm.put("空调", 1100); hm.put("热水器", 1400); for(Entry<String, Integer> kv : hm.entrySet()) { System.out.println(kv.getKey() + ":" + kv.getValue()); }
运行结果
修改元素
示例
HashMap<String, Integer> hm = new HashMap<>(); hm.put("电冰箱", 1000); hm.put("洗衣机", 900); hm.put("电视机", 1000); hm.put("空调", 1100); hm.put("热水器", 1400); // 把电冰箱的价格修改成1500元 hm.put("电冰箱", 1500); for(Entry<String, Integer> kv : hm.entrySet()) { System.out.println(kv.getKey() + ":" + kv.getValue()); }
运行结果
获取元素
示例
HashMap<String, Integer> hm = new HashMap<>(); hm.put("电冰箱", 1000); hm.put("洗衣机", 900); hm.put("电视机", 1000); hm.put("空调", 1100); hm.put("热水器", 1400); // 获得洗衣机的价格 int price = hm.get("洗衣机"); System.out.println(price);
运行结果
移除元素
示例
HashMap<String, Integer> hm = new HashMap<>(); hm.put("电冰箱", 1000); hm.put("洗衣机", 900); hm.put("电视机", 1000); hm.put("空调", 1100); hm.put("热水器", 1400); // 移除 电冰箱和空调 hm.remove("电冰箱"); hm.remove("空调"); for(Entry<String, Integer> kv : hm.entrySet()) { System.out.println(kv.getKey() + ":" + kv.getValue()); } System.out.println("---------------"); // 移除所有元素 hm.clear(); System.out.println(hm.size());
运行结果
判断相关
示例
HashMap<String, Integer> hm = new HashMap<>(); hm.put("电冰箱", 1000); hm.put("洗衣机", 900); hm.put("电视机", 1000); hm.put("空调", 1100); hm.put("热水器", 1400); // 判断是否包含 “空调” 的键 boolean result = hm.containsKey("空调"); System.out.println("containsKey(Object key) :" + result); // 判断是否包含 “1000” 的值 result = hm.containsValue(1000); System.out.println("containsValue(Object value) :" + result); // 判断集合是否为空 result = hm.isEmpty(); System.out.println("isEmpty() :" + result);
运行结果
遍历集合元素
keySet 方式遍历
- 调用keySet() 方法,返回一个Set集合,这个集合中存储了所有的键,然后遍历Set集合,通过键获得值。
示例
HashMap<String, Integer> hm = new HashMap<>(); hm.put("电冰箱", 1000); hm.put("洗衣机", 900); hm.put("电视机", 1000); hm.put("空调", 1100); hm.put("热水器", 1400); Set<String> keySet = hm.keySet(); for(String key : keySet) { System.out.println(key + " : " + hm.get(key)); }
运行结果
entrySet 遍历
- 调用 entrySet() 方法,获得所有的键值对
示例
HashMap<String, Integer> hm = new HashMap<>(); hm.put("电冰箱", 1000); hm.put("洗衣机", 900); hm.put("电视机", 1000); hm.put("空调", 1100); hm.put("热水器", 1400); for(Entry<String, Integer> kv : hm.entrySet()) { System.out.println(kv.getKey() + " : " + kv.getValue()); }
运行结果