java中Map的遍历

Map遍历的常用方法

Map<Integer, String> map = new HashMap<Integer, String>(); 
map.put(0, "zero");
map.put(1, "one");
map.put(2, "two");

 

方法一:最常用的

// 获取key值
Collection<Integer> k = map.keySet();        
Iterator<Integer> itK= k.iterator();  
System.out.println(k);
for (; itK.hasNext();) {            
	System.out.println(itK.next());        
}

运行结果:

[0, 1, 2]

      0

      1

      2

//获取value值
Collection<String> v = map.values();        
Iterator<String> itV = v.iterator();  
System.out.println(v);
for (; itV.hasNext();) {            
	System.out.println(itV.next());        
}


 

运行结果:

[zero, one, two]

      zero

      one

      two

 

方法二:根据key值得到value

Set<Integer> key = map.keySet();        
for (Iterator<Integer> it = key.iterator(); it.hasNext();) {            
	Integer s =  (Integer)it.next();   
	System.out.println(s);
	System.out.println(map.get(s));        
}

运行结果:

 0

zero

 1

one

 2

Two

 

方法三:比较复杂,但灵活性强

Set<Map.Entry<Integer, String>> set = map.entrySet(); 
for (Iterator<Map.Entry<Integer, String>> it = set.iterator(); it.hasNext();) {            
	Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) it.next();
	System.out.println(entry.getKey() + "--->" + entry.getValue());        
}

运行结果:

0--->zero

1--->one

2--->two

 

参考网址:http://zhidao.baidu.com/question/283029340.html

 

 

 

你可能感兴趣的:(java,map,遍历)