遍历Map的三种方式

来源:互联网 发布:阴阳师数据分析 编辑:程序博客网 时间:2024/06/06 01:19

public static void main(String[] args) {


Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");


// 第一种:
System.out.println("第一种:通过Map.keySet遍历key和value:");
System.out.println("1.用迭代器的");
Set<String> set = map.keySet();
Iterator<String> it1 = set.iterator();
while (it1.hasNext()) 
{
String key = it1.next();
System.out.println(key + " " + map.get(key));
}


System.out.println("2.用for循环的");
for (String key : map.keySet()) 
{
System.out.println(key + " " + map.get(key));
}


// 第二种:
System.out.println("第二种:通过Map.entrySet使用遍历key和value:");
System.out.println("1.用迭代器的");
Iterator<Map.Entry<String, String>> it2 = map.entrySet().iterator();
while (it2.hasNext()) 
{
Map.Entry<String, String> entry = it2.next();
System.out.println(entry.getKey() + " " + entry.getValue());
}


System.out.println("2.用for循环的");
for (Map.Entry<String, String> entry : map.entrySet()) 
{
System.out.println(entry.getKey() + " " + entry.getValue());
}


// 第三种:
System.out.println("第三种:通过Map.values()遍历所有的value,但不能遍历key");
for (String v : map.values()) 
{
System.out.println(v);
}


}