集合中,使用迭代器遍歷的方法
阿新 • • 發佈:2019-01-29
目錄
1.使用迭代器遍歷List集合
package com.jredu.oopch07; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Ch05 { public static void main(String[] args) { List list = new ArrayList<>(); //集合 list.add(1); list.add(2); list.add(3); //Iterator迭代器 //1、獲取迭代器 Iterator iter = list.iterator(); //2、通過迴圈迭代 //hasNext():判斷是否存在下一個元素 while(iter.hasNext()){ //如果存在,則呼叫next實現迭代 //Object-->Integer-->int int j=(int)iter.next(); //把Object型強轉成int型 System.out.println(j); } } }
2.使用迭代器遍歷Set集合
package com.jredu.oopch08; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class Ch01 { public static void main(String[] args) { //儲存資料的地址 Set set = new HashSet<>(); //儲存資料 set.add(new Theme(1,"標題1","簡介1")); set.add(new Theme(2,"標題2","簡介1")); //遍歷資料 Iterator iter = set.iterator(); while(iter.hasNext()){ Theme theme = (Theme)iter.next(); System.out.println(theme.getId()+theme.getTitle()+theme.getRemark()); } } }
3.使用迭代器遍歷Map集合
3.1使用map中的keySet( )方法進行獲取
public class Ch04 { public static void main(String[] args) { Map map=new HashMap<>(); map.put(1, "a"); map.put(2, "b"); map.put(3, "c"); //必須掌握 //所有鍵值對中的鍵,組成成一個set集合 Set set=map.keySet(); //迭代鍵的集合 Iterator it = set.Iterator(); while(it.hashNext()){ Object key = it.next(); //獲得每個鍵所對應的值 object value = map.get(key); system.out.println(key+"="+value); } }
3.2使用map中的entrySet進行遍歷
public class Ch04 {
public static void main(String[] args) {
Map map=new HashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
Set set=map.entrySet();
Iterator it = set.Iterator();
while(it.hashNext()){
Map.entry entry = (Map.entry)it.next();
object key= entry.getKey();
object value = entyr.getValue();
system.out.println(key+"="+value);
}
}