Map
Collection与Map
一、Map常用子类
- HashMap:
存储数据采用的哈希表结构,元素的存取顺序不能保证一致。由于要保证键的唯一、不重复,需要重写键的hashCode()方法、equals()方法。 - LinkedHashMap:
存储数据采用的哈希表结构+链表结构。通过链表结构可以保证元素的存取顺序一致;通过哈希表结构可以保证的键的唯一、不重复,需要重写键的hashCode()方法、equals()方法。
二、Map接口中的常用方法
- public V put(K key, V value) : 把指定的键与指定的值添加到Map集合中。
- public V remove(Object key) : 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值。
- public V get(Object key) 根据指定的键,在Map集合中获取对应的值。
- public Set keySet() : 获取Map集合中所有的键,存储到Set集合中。
- public Set<Map.Entry<K,V>> entrySet() : 获取到Map集合中所有的键值对对象的集合(Set集合)。
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
//添加元素到集合
map.put("黄晓明", "杨颖");
map.put("文章", "马伊琍");
System.out.println(map.remove("文章"));//马伊琍(通过键移除对应的键值对元素并返回被删除的值)
System.out.println(map.get("黄晓明"));//杨颖 (查看“黄晓明”对应的value值)
Set<String> keys = map.keySet();//获得Map集合中所有的键存到Set集合中
System.out.println(keys);//[邓超, 黄晓明]
Set<Map.Entry<String, String>> entries = map.entrySet();//获得Map集合中所有的键值对对象的集合
System.out.println(entries);//[邓超=孙俪, 黄晓明=杨颖]
}
使用put方法时,若指定的键(key)在集合中没有,则没有这个键对应的值,返回null,并把指定的键值添加到集合中;
若指定的键(key)在集合中存在,则返回值为集合中键对应的值(该值为替换前的值),并把指定键所对应的值,替换成指定的新值。
三、键找值遍历Map集合
//接上个代码
for (String key : keys) {
String value = map.get(key);//获取键对应的值
System.out.println(key+"的value值是:"+value);
}
四、键值对方式遍历Map集合
Map中的key和value是一一对应关系,Entry 将键值对的对应关系封装成了对象。即键值对对象,这样我们在遍历 Map 集合时,就可以从每一个键值对( Entry )对象中获取对应的键与对应的值。
- public K getKey() :获取Entry对象中的键。
- public V getValue() :获取Entry对象中的值。
//接上面代码
for (Map.Entry<String, String> entry : entries) {
System.out.println("key值:" + (entry.getKey() + " value值:" + entry.getValue()));
}
输出结果:
key值:邓超 value值:孙俪
key值:黄晓明 value值:杨颖
五、HashMap存储自定义类型
要在自定义类中重写hashCode()方法、equals()方法。
public class Student {
private String name;
private int age;
//此处省略了构造和get、set方法
@Override
public 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);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
Map<Student,String>map = new HashMap<Student,String>();
//添加元素。
map.put(newStudent("lisi",28), "上海");
map.put(newStudent("wangwu",22), "北京");
map.put(newStudent("zhaoliu",24), "成都");
六、LinkedHashMap
保证有序
public class LinkedHashMapDemo {
public static void main(String[] args) {
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put("邓超", "孙俪");
map.put("李晨", "范冰冰");
map.put("刘德华", "朱丽倩");
Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
结果:
邓超 孙俪
李晨 范冰冰
刘德华 朱丽倩