关于Map集合的遍历总结
转:http://www.cnblogs.com/lsgspace/p/4666020.html
以下是遍历Map集合的几种方式:
public static void main(String[] args)
{
Map<String, String> map = new HashMap<String, String>();
map.put("1", "张三");
map.put("2", "李四");
map.put("3", "王五");
//调用
}
1、通过Map.keySet遍历key和value
private static void findKey(Map<String, String> map)
{
System.out.println("findKey");
for (String key : map.keySet())
{
System.out.println("key = " + key);
System.out.println("value = " + map.get(key));
}
}
2、通过Map.values遍历value
private static void findValue(Map<String, String> map)
{
System.out.println("findValue");
for (String value : map.values())
{
System.out.println("value = " + value);
}
}
3、通过Map.entrySet和迭代器遍历Map
private static void findIterator(Map<String, String> map)
{
System.out.println("findIterator");
Iterator<Map.Entry<String, String>> carIterator = map.entrySet().iterator();
while (carIterator.hasNext())
{
Map.Entry<String, String> entry = carIterator.next();
System.out.println("key = " + entry.getKey());
System.out.println("value = " + entry.getValue());
}
}
4、Map.entrySet加for in 循环(推荐)
private static void findEntrySet(Map<String, String> map)
{
System.out.println("findEntrySet");
for (Entry<String, String> entry : map.entrySet())
{
System.out.println("key = " + entry.getKey());
System.out.println("value = " + entry.getValue());
}
}