现在的位置: 首页 > 综合 > 正文

遍历map中的元素的几种方法

2013年02月25日 ⁄ 综合 ⁄ 共 898字 ⁄ 字号 评论关闭

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

/**
 * 遍历map的几种方法
 * @author tpf
 *
 */
public class TestMapLookup {
 
 public static void main(String[] args) {
   Map <String,Integer> map = new HashMap<String,Integer>();
   map.put("aaa", 1);
   map.put("ccc", 2);
   map.put("bbb", 3);
  
   //方法一for
  for(Map.Entry<String,Integer> entry: map.entrySet()){
   System.out.println(entry.getKey() + "--->" + entry.getValue());
  }
  
  //方法二keySet()
  Set<String> set = map.keySet();
  Iterator <String> it = set.iterator();
   while(it.hasNext()) {
    String key = it.next();
    int value = map.get(key);
    System.out.println(key + "--->" + value);
   }
  
   //方法三entrySet()
   Set<Map.Entry<String, Integer>> set1 = map.entrySet();
   Iterator <Map.Entry<String, Integer>> it1 = set1.iterator();
   while(it1.hasNext()) {
    Map.Entry<String, Integer> entry = it1.next();
    System.out.println(entry.getKey() + "---->" + entry.getValue());
   }
 } 
}

抱歉!评论已关闭.