Java中map的四种遍历方式,适用于所有map。
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Mapbianli {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String,Integer> map=new HashMap<String,Integer>();
map.put("lihua", 18);
map.put("liming", 17);
//第一种遍历方式,在for循环中遍历key或者values,一般适用于只需要map中的key或者value时使用
//遍历key
for(String key:map.keySet())
{
System.out.println(key);
}
//遍历value
for(Integer value:map.values())
{
System.out.println(value);
}
System.out.println("=============");
//第二种遍历方式,在for循环中使用entries实现Map的遍历
for(Map.Entry<String,Integer> entry:map.entrySet())
{
System.out.println(entry.getKey()+":"+entry.getValue());
}
System.out.println("=============");
//第三种遍历方式,通过Iterator遍历;
Iterator<Map.Entry<String, Integer>> it= map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, Integer> entry2 =it.next();
System.out.println(entry2.getKey()+":"+entry2.getValue());
}
System.out.println("=============");
//第四种遍历方式,通过键找值遍历
for(String key : map.keySet()){
Integer value = map.get(key);
System.out.println(key+":"+value);
}
}
}
map的四种遍历方式中,第一种效率最高,第四种涉及到用键找值,性能最低。
四种遍历方式涉及到两种思想,一种是通过keySet直接获取键进而获取值;另一种是通过entrySet获得Key和Value的映射关系(Map.Entry),再从这个关系中得到对应的key和value值
可参考另外一个人的文章https://blog.csdn.net/qianfeng_dashuju/article/details/79196184