最近在做项目时用到了Map,发现对Map的用法并不是很上手,所以今天就抽时间总结一下Map。
查看API得知,Map是一个接口,是将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射到一个值。
1、遍历Map
遍历Map常用的有两种方法,第1种代码如下:
Map<String,String> map = new HashMap<>();
map.put("username", "zhang");
map.put("password", "123");
map.put("id", "5");
map.put("email", "123456@qq.com");
for(Map.Entry<String, String> entry : map.entrySet()){
System.out.println(entry.getKey()+"::"+entry.getValue());
}
打印结果:
id::5
username::zhang
email::123456@qq.com
password::123
代码很简单,类似于增强for循环。观察打印结果我们可得知,遍历Map的循序跟添加Map键值对的循序无关。
第2种:
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()){
Entry<String, String> entry = it.next();
System.out.println(entry.getKey()+"::"+entry.getValue());
}
打印结果同上。
2、删除Map中的元素。
当使用第一种遍历Map删除某个元素时,会报异常。删除代码:
for(Map.Entry<String, String> entry : map.entrySet()){
if(entry.getKey().equals("id")){
map.remove(entry.getKey());
}
System.out.println(entry.getKey()+"::"+entry.getValue());
}
运行后报并发修改异常:java.util.ConcurrentModificationException。通过查资料得知,这种for循环无法修改map内容,因为不通过迭代器。使用第二种遍历Map方法可删除某个元素:
Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String, String> entry = iterator.next();
if(entry.getKey().equals("id")){
iterator.remove();
}
}
删除所有元素直接调用clear()方法就可以了。