---
title: "Java - 如何遍历Map中的内容"
author: "topsale"
date: "2011-04-11T15:29:13Z"
tags: []
categories: ["编程语言"]
slug: "java-map"
draft: false
lastmod: "2011-04-12T10:02:00Z"
id: 997847
url: "https://topsale.iteye.com/blog/997847"
---

Map的遍历很简单，不过在JDK1.5中有新的方法可以遍历，相信有很多外包的同仁用的还是JDK1.4版吧，呵呵，这里就分别写出如何在JDK1.5(1.6..)和JDK1.4中遍历Map。

JDK1.4中代码如下：

```java

	public static void main(String[] args) {
		Person numOne = new Person();
		numOne.setName("Lusifer");
		numOne.setAge(25);

		Person numTwo = new Person();
		numTwo.setName("Main");
		numTwo.setAge(25);

		Person numThree = new Person();
		numThree.setName("Ted");
		numThree.setAge(25);

		try {
			numOne.setBrithday(new SimpleDateFormat("yyyy-MM-dd").parse("1986-07-31"));
			numTwo.setBrithday(new SimpleDateFormat("yyyy-MM-dd").parse("1986-08-31"));
			numThree.setBrithday(new SimpleDateFormat("yyyy-MM-dd").parse("1989-08-31"));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		Map map = new HashMap();
		map.put("numOne", numOne);
		map.put("numTwo", numTwo);
		map.put("numThree", numThree);

		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			//Object key = entry.getKey();
			//Object value = entry.getValue();
			
			Person p = (Person) entry.getValue();
			System.out.println(p.getName());
		}
	}

```


JDK1.5中代码如下：

```java

	public static void main(String[] args) {
		Person numOne = new Person();
		numOne.setName("Lusifer");
		numOne.setAge(25);
		
		Person numTwo = new Person();
		numTwo.setName("Main");
		numTwo.setAge(25);
		
		Person numThree = new Person();
		numThree.setName("Ted");
		numThree.setAge(25);
		
		try {
			numOne.setBrithday(new SimpleDateFormat("yyyy-MM-dd").parse("1986-07-31"));
			numTwo.setBrithday(new SimpleDateFormat("yyyy-MM-dd").parse("1986-08-31"));
			numThree.setBrithday(new SimpleDateFormat("yyyy-MM-dd").parse("1989-08-31"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("numOne", numOne);
		map.put("numTwo", numTwo);
		map.put("numThree", numThree);
		
		//加入了foreach的特性，这里方便多了
		for (Object o : map.keySet()) {
			Person p = (Person) map.get(o);
			System.out.println(p.getName());
		}
	}

```