遍歷MAP的四種方法(增強for迴圈)
阿新 • • 發佈:2019-01-28
增強for迴圈:
設計的本意:拋棄迭代器增強for迴圈只能遍歷陣列和實現了Iteratable介面的物件。
語法:
for(元素的型別 變數名:陣列或實現了Iteratable介面的物件){
System.out.println(變數名);
}
增強for迴圈的特點:只適合取資料。要想在遍歷時改元素的值,請使用傳統for迴圈。
遍歷MAP的四種方法:
//增強for迴圈 public class Demo { //傳統方式遍歷Map @Test public void test3(){ Map map = new LinkedHashMap(); map.put("a", "aaa"); map.put("b", "bbb"); map.put("c", "ccc"); Set keys = map.keySet(); Iterator it = keys.iterator(); while(it.hasNext()){ String key = (String)it.next(); String value = (String) map.get(key); System.out.println(key+"="+value); } } @Test//增強for遍歷map方式一 public void test31(){ Map map = new LinkedHashMap(); map.put("a", "aaa"); map.put("b", "bbb"); map.put("c", "ccc"); Set keys = map.keySet(); for(Object obj:keys){ String key = (String)obj; String value = (String) map.get(key); System.out.println(key+"="+value); } } //傳統方式遍歷Map @Test public void test4(){ Map map = new LinkedHashMap(); map.put("a", "aaa"); map.put("b", "bbb"); map.put("c", "ccc"); Set me = map.entrySet(); Iterator it = me.iterator(); while(it.hasNext()){ Map.Entry m = (Map.Entry)it.next(); String key = (String) m.getKey(); String value = (String)m.getValue(); System.out.println(key+"="+value); } } @Test//增強for迴圈遍歷map方式二 public void test41(){ Map map = new LinkedHashMap(); map.put("a", "aaa"); map.put("b", "bbb"); map.put("c", "ccc"); for(Object obj:map.entrySet()){ Map.Entry me = (Map.Entry )obj; String key = (String) me.getKey(); String value = (String)me.getValue(); System.out.println(key+"="+value); } } }