Java 里的Map不支持Iterable接口,所以不能直接使用foreach对其内的所有元素进行遍历,需要先转成支持Iterable接口的set:
1. 通过 entrySet 取得所有 entry,每个entry都可以通过 getKey() 和 getValue() 来取得 key 和 value 值。
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class MapTest {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
for(Entry<Integer, String>e: map.entrySet()){
System.out.println(e.getKey() + ":" + e.getValue());
}
}
}
/* out put->
1:one
2:two
3:three
*/
2. 通过 keySet 取得所有 Key,然后通过 get () 来取得每个 value。
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class MapTest {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
for(Integer k: map.keySet()){
System.out.println(k + ":" + map.get(k));
}
}
}
/* out put->
1:one
2:two
3:three
*/
JAVA 6 MAP API:http://docs.oracle.com/javase/6/docs/api/java/util/Map.html
环境: JDK1.6.0_30