原文:http://chevy.iteye.com/blog/1446786
第一种:把值放到一个集合里,然后遍历集合
public class TraversalMap1 {
private static final Map<Integer, String> map;
static {
map = new HashMap<Integer, String>();
map.put(1, "value1");
map.put(2, "value2");
map.put(3, "value3");
map.put(4, "value4");
}
public static void main(String[] args) {
Collection<String> c = map.values();
Iterator<String> i = c.iterator();
for (; i.hasNext();) {
System.out.println(i.next());// 遍历出map内的所有value
}
}
}
第二种:利用keyset进行遍历。
public class TraversalMap2 {
private static final Map<Integer, String> map;
static {
map = new HashMap<Integer, String>();
map.put(1, "value1");
map.put(2, "value2");
map.put(3, "value3");
map.put(4, "value4");
}
public static void main(String[] args) {
Set<Integer> set = map.keySet();
Iterator<Integer> i = set.iterator();
for (; i.hasNext();) {
System.out.println(i.next());// 遍历出map内的所有key
}
}
}
第三种:利用entrySet进行遍历。
public class TraversalMap3 {
private static final Map<Integer, String> map;
static {
map = new HashMap<Integer, String>();
map.put(1, "value1");
map.put(2, "value2");
map.put(3, "value3");
map.put(4, "value4");
}
public static void main(String[] args) {
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("the map key is : " + entry.getKey() + " || the value is : "
+ entry.getValue());// 显示出map的key和value
}
}
}