wen742538485 发表于 2013-2-3 13:59:26

遍历Map的四种方法

public static void main(String[] args) {

Map<string string> map = new HashMap<string string>();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");

//第一种:普遍使用,二次取值
System.out.println("通过Map.keySet遍历key和value:");
for (String key : map.keySet()) {
   System.out.println("key= "+ key + " and value= " + map.get(key));
}

//第二种
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
Iterator<map.entry string>> it = map.entrySet().iterator();
while (it.hasNext()) {
   Map.Entry<string string> entry = it.next();
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}

//第三种:推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry<string string> entry : map.entrySet()) {
   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四种
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for (String v : map.values()) {
   System.out.println("value= " + v);
}
}


//-----Test start-----
   PriceInfoDao pdao=new PriceInfoDao(pub);
   Date date = new Date("2010/12/27");         
   hqmap= pdao.getCheckjjhzhqInfo(2010, 1, date,"0");
   PriceInfo pinfo=new PriceInfo();
   pinfo.setFZQDM("000006");
   pinfo.setFSZSH("Y");
   pinfo=(PriceInfo)hqmap.get(pinfo);
   System.out.println("Value="+pinfo.getFZQDM()+"\t"+pinfo.getFSZSH()+"\t"+pinfo.getFSETCODE());
   
//循环遍历Map 集合
   Map.Entry map=null;
   Set   set   =   hqmap.entrySet();
   Iterator   i   = set.iterator();
      while(i.hasNext()){
       map=(Map.Entry)i.next();
       pinfo=(PriceInfo)map.getValue();
       //System.out.println("Key:"+map.getKey()+"==Value:"+map.getValue());
                   System.out.println("Value:"+pinfo.getFZQDM()+"_"+ pinfo.getFSETCODE()+"_"+pinfo.getFSZSH());
                }
   //---end---</string></string></map.entry></string></string>
页: [1]
查看完整版本: 遍历Map的四种方法