Map接口
方法:
- public V put(K key, V value): 把指定的键与指定的值添加到Map集合中。
- public V remove(Object key): 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值。
- public V get(Object key) 根据指定的键,在Map集合中获取对应的值。
- boolean containsKey(Object key) 判断集合中是否包含指定的键。
- public Set
keySet(): 获取Map集合中所有的键,存储到Set集合中。 - public Set
> entrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)
其他方法
put(K key, V value) 有添加和替换功能putAll(Map m) 添加一个Map的元素clear() 清空集合remove(Object key) 根据键删除一个元素containsKey() 判断集合是否包含指定的键containsValue() 判断集合是否包含指定的值isEmpty() 判断集合是否为空get(Object key) 根据键获取值keySet() 获取所有的键values() 获取所有的值size() 获取集合元素的个数
遍历
三种遍历方式
public class HashMapIterator {public static void main(String[] args) {Map<String, Integer> map = new HashMap<>();map.put("a", 1);map.put("b", 2);map.put("c", 3);//迭代器Set<String> set = map.keySet();Iterator<String> it = set.iterator();while (it.hasNext()) {String key = it.next();Integer value = map.get(key);System.out.println(key + "--->" + value);}//for setfor (String key : map.keySet()) {Integer value = map.get(key);System.out.println(key + "--->" + value);}// for entryfor (Map.Entry<String, Integer> e : map.entrySet()) {System.out.println(e.getKey() + "--->" + e.getValue());}}}
Entry/键值对对象
Map中存放的是两种对象,一种称为key(键),一种称为value(值),它们在在Map中是一一对应关系,这一对对象又称做Map中的一个Entry(项)。Entry将键值对的对应关系封装成了对象。即键值对对象,这样我们在遍历Map集合时,就可以从每一个键值对(Entry)对象中获取对应的键与对应的值。
既然Entry表示了一对键和值,那么也同样提供了获取对应键和对应值得方法:
public K getKey():获取Entry对象中的键。public V getValue():获取Entry对象中的值。
在Map集合中也提供了获取所有Entry对象的方法:
public Set<Map.Entry<K,V>> entrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)。
eg
public static void main(String[] arge){HashMap<String,String> map = new HashMap<String,String>();map.put("北京","北京");map.put("广东","广州");map.put("山东","济南");map.put("浙江","杭州");map.put("江苏","杭州");Set<Entry<String,String>> set = map.entrySet();for (Entry<String,String> entry: set){System.out.println(entry.getKey()+":"+entry.getValue());}}
存储自定义对象
@Overridepublic boolean equals(Object o) {if (this == o)return true;if (o == null || getClass() != o.getClass())return false;Student student = (Student) o;return age == student.age && Objects.equals(name, student.name);}@Overridepublic int hashCode() {return Objects.hash(name, age);}
LinkedHashMap
我们知道HashMap保证成对元素唯一,并且查询速度很快,可是成对元素存放进去是没有顺序的,那么我们要保证有序,还要速度快怎么办呢?在HashMap下面有一个子类LinkedHashMap,它是链表和哈希表组合的一个数据存储结构。
public static void main(String[] arg) {LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();map.put("中国", "CHN");map.put("美国", "USA");map.put("俄罗斯", "RUS");map.put("法国", "FRA");map.put("英国", "UK");Set<Entry<String, String>> entrySet = map.entrySet();for (Entry<String, String> entry : entrySet) {System.out.println(entry.getKey() + " " + entry.getValue());}}
