109.【JAVA编程】HashMap循环

1.键值都需要时使用

1.1键值都需要时使用

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
	System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

1.2用for-each循环中遍历keys或values

 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
 //遍历map中的键 
 for (Integer key : map.keySet()) { 
   System.out.println("Key = " + key); 
 } 
 //遍历map中的值 
 for (Integer value : map.values()) { 
   System.out.println("Value = " + value); 
 } 
该方法比entrySet遍历在性能上稍好(快了10%),而且代码更加干净

1.3使用Iterator遍历

使用泛型:
 Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
 Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); 
 while (entries.hasNext()) { 
   Map.Entry<Integer, Integer> entry = entries.next(); 
   System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
 } 
不使用泛型:
 Map map = new HashMap(); 
 Iterator entries = map.entrySet().iterator(); 
 while (entries.hasNext()) { 
   Map.Entry entry = (Map.Entry) entries.next(); 
   Integer key = (Integer)entry.getKey(); 
   Integer value = (Integer)entry.getValue(); 
   System.out.println("Key = " + key + ", Value = " + value); 
 } 

1.4使用通过键找值遍历(效率低)

Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
 for (Integer key : map.keySet()) { 
   Integer value = map.get(key); 
   System.out.println("Key = " + key + ", Value = " + value); 
}

1.5for的另一种格式

for (Iterator i = tempMap.keySet().iterator(); i.hasNext();) {
   Object obj = i.next();
   System.out.println(obj);// 循环输出key
   System.out.println("key=" + obj + " value=" + tempMap.get(obj));
  }
  for (Iterator i = tempMap.values().iterator(); i.hasNext();) {
   Object obj = i.next();
   System.out.println(obj);// 循环输出value
  }

你可能感兴趣的:(【JAVA】)