【備忘】遍歷Map的方法,包括1.4和1.5兩版本

直接上代碼:


編譯用1.4,可用如下方法遍歷

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
Object key = entry.getKey();
Object value = entry.getValue();
}


以下爲1.5新特性遍歷

import java.util.HashMap;
import java.util.Map;

/**
* Map的遍歷
*
* @author wasw100
*/
public class MapTest {

public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("one", 1);
map.put("two", 2);

// 通過Map.keySet取得鍵的集合
System.out.println("通過Map.keySet遍歷:");
for (String key : map.keySet()) {
System.out.println("鍵:" + key + "\t值:" + map.get(key));
}

// 通過Map.entrySet遍歷
System.out.println();
System.out.println("通過Map.entrySet遍歷:");
for (Map.Entry<String, Integer> s : map.entrySet()) {
System.out.println("鍵:" + s.getKey() + "\t值:" + s.getValue());
}

// 通過Map.values()遍歷所有的值,但是不能遍歷鍵
System.out.println();
System.out.println("通過Map.values()遍歷所有的值:");
for (Object o : map.values()) {
Integer i = (Integer) o;
System.out.println("值:" + i);
}

}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章