第一种遍历方式: 利用entrySet()
package com.yidong.map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapDemo01 {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(1, "jitui");
map.put(2, "dabing");
map.put(5, "xiangchang");
map.put(3, "xiangchang");
map.put(4, "regou");
Set<Entry<Integer, String>> entrySet = map.entrySet();
/*for (Entry<Integer, String> entry : entrySet) {
System.out.println(entry.getKey()+":"+entry.getValue());
}*/
/*for (Iterator iterator = entrySet.iterator(); iterator.hasNext();) {
Entry<Integer, String> entry = (Entry<Integer, String>) iterator.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}*/
Iterator<Entry<Integer, String>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Map.Entry<Integer,String> entry = (Map.Entry<Integer, String>) iterator
.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}
第二种遍历方式:通过keySet()
Map<Integer,String> map=new HashMap<Integer,String>();
map.put(1, "jitui");
map.put(2, "dabing");
map.put(5, "xiangchang");
map.put(3, "xiangchang");
map.put(4, "regou");
Set<Integer> keySet = map.keySet();
/*for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
Integer key = (Integer) iterator.next();
System.out.println(key+":"+map.get(key));
}*/
/* Iterator<Integer> iterator = keySet.iterator();
while (iterator.hasNext()) {
Integer key = (Integer) iterator.next();
System.out.println(key+":"+map.get(key));
}
*/
for (Integer key : keySet) {
System.out.println(key+":"+map.get(key));
}
第三种遍历方式:values()
```java
Collection<String> values = map.values();//只能遍历值 不能得到键
//6种 iterator +while iterator+for foreach ArrayList
for (String value : values) {
System.out.println(value);
}