您的位置:首页 > 其它

遍历Map的三种方式:

2010-04-28 17:10 190 查看
 

public static void main(String[] args) {
//创建HashMap实例
Map map=new HashMap();
//向map中添加数据
map.put("1","a");
map.put("2","b");
map.put("3","c");
map.put("4","d");
map.put("5","e");

方式一:
//转换key值为Set
Set set=map.keySet();
//把Set转换成数组
Object[] arr=set.toArray();
//遍历数组,根据key值输出value值
for(int i=0;i<arr.length;i++){
String value=(String)map.get(arr[i]);
System.out.println(value);
}

方式二:
for(Iterator it = map.keySet().iterator(); it.hasNext();)
     { 
       String lkey = it.next().toString(); //名
       String lvalue = (String)map.get(lkey);//值
       System.out.println("名: "+lkey+" = 值: "+lvalue);
     }

方式三:
Iterator it = map.keySet().iterator();
while( it.hasNext())
     { 
       String lkey = it.next().toString(); //名
       String lvalue = (String)map.get(lkey);//值
       System.out.println("名: "+lkey+" = 值: "+lvalue);
     }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: