---
title: "Map 3种遍历"
author: "alwarse"
date: "2012-10-22T15:12:52Z"
tags: []
categories: ["编程语言"]
slug: "map-3"
draft: false
lastmod: "2012-10-22T15:12:52Z"
id: 1703025
url: "https://alwarse.iteye.com/blog/1703025"
---

Map的遍历有3种：

**1、遍历Map.entrySet()：**它的每一个元素都是Map.Entry对象，这个对象中，

放着的就是Map中的某一对key-value；

**2、遍历Map.keySet()：**它是Map中key值的集合，我们可以通过遍历这个集合来

读取Map中的元素；

**3、遍历Map.values()：**它是Map中value的集合，我们可以直接通过这个集合遍历

Map中的值，却不能读取key。

**代码：**

package com.csct.test.map;

import java.util.HashMap;  
import java.util.Iterator;  
import java.util.Map;  
import java.util.TreeMap;

public class TestMapIter {

   
 public static void main(String\[] args) {  
    
  Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();  
  //Map&lt;String, String&gt; map = new TreeMap&lt;String, String&gt;();  
  TestMapIter testMapIter = new TestMapIter();  
  testMapIter.initData(map);  
    
  System.out.println("------Map遍历方法------");  
  // 1.1  
  Iterator iterator = map.entrySet().iterator();  
  while(iterator.hasNext()) {  
   Map.Entry entry = (Map.Entry)iterator.next();  
   System.out.println(entry.getKey()+"---"+entry.getValue());  
  }  
  // 1.2  
  for(Map.Entry entry:map.entrySet()) {  
   System.out.println(entry.getKey()+"---"+entry.getValue());  
  }  
    
  System.out.println("--------------------------");  
  // 2.1 遍历key值  
  for(Object o:map.keySet()) {  
   System.out.println(map.get(o));  
  }  
  // 2.2 遍历value值  
  for(Object o:map.values()) {  
   System.out.println(o);  
  }  
 }

 private void initData(Map&lt;String, String&gt; map) {  
  map.put("key3", "value3");  
  map.put("key1", "value1");  
  map.put("key2", "value2");  
  map.put("keyb", "valueB");  
  map.put("keya", "valueA");  
 }  
}