1、使用增強的for迴圈 此種方式可以遍歷所有集合,但使用的是臨時變數,只能訪問集合元素,不能修改。 2、Collection集合可以使用自身的 forEach(Consumer action)方法,Consumer是一個函數式介面,只需實現 accept(element)方法。 此方式只能用於Co ...
1、使用增強的for迴圈
1 HashMap hashMap=new HashMap(); 2 hashMap.put("name","張三"); 3 hashMap.put("age",12); 4 hashMap.put("score",90); 5 for (Object key:hashMap.keySet()){ 6 System.out.println(key+" --> "+hashMap.get(key)); 7 }
此種方式可以遍歷所有集合,但使用的是臨時變數,只能訪問集合元素,不能修改。
2、Collection集合可以使用自身的 forEach(Consumer action)方法,Consumer是一個函數式介面,只需實現 accept(element)方法。
1 HashSet hashSet=new HashSet(); 2 hashSet.add("張三"); 3 hashSet.add("李四"); 4 hashSet.add("王五"); 5 //參數表示當前元素 6 hashSet.forEach(ele-> System.out.println(ele));
此方式只能用於Collection集合。
3、Map集合也可以使用自身的forforEach(BiConsumer action),BiConsumer是一個函數式介面,只需要實現accept(key,value)方法。
1 HashMap hashMap=new HashMap(); 2 hashMap.put("name","張三"); 3 hashMap.put("age",18); 4 hashMap.put("score",90); 5 //2個參數,一個代表鍵,一個代表對應的值 6 hashMap.forEach((key,value)-> System.out.println(key+" --> "+value));
此方式只能用於Map集合。
4、使用Iterator介面
Iterator即迭代器,可用的4個方法:
boolean hasNext()
Object next() 獲取下一個元素
void remove() 刪除當前元素
void forEachRemaining(Consumer action) 可以使用Lambda表達式遍歷集合
1 HashSet hashSet=new HashSet(); 2 hashSet.add("張三"); 3 hashSet.add("李四"); 4 hashSet.add("王五"); 5 //獲取迭代器對象 6 Iterator iterator=hashSet.iterator(); 7 while (iterator.hasNext()){ 8 System.out.println(iterator.next()); 9 }
1 HashSet hashSet=new HashSet(); 2 hashSet.add("張三"); 3 hashSet.add("李四"); 4 hashSet.add("王五"); 5 //獲取迭代器對象 6 Iterator iterator=hashSet.iterator(); 7 iterator.forEachRemaining(element-> System.out.println(element));
以上兩種方式效果完全相同。
說明:
Collection集合才能使用此方式,因為Collection集合才提供了獲取Iterator對象的方法,Map未提供。
List集合還可以使用 listIterator() 獲取 ListIterator對象,ListIterator是Iterator的子介面,使用方式和Iterator完全相同,只是ListIterator還提供了其它方法。
在迴圈體中不能使用集合本身的刪除方法來刪除元素,會發生異常。要刪除,只能使用Iterator類提供的remove()方法來刪除。