遍历集合的方式
一、传统for循环
public static void main(String[] args) { List list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); //1、for循环遍历List for (int i = 0;i<list.size();i++){ System.out.println(list.get(i)); } }
输出结果:
a b c d Process finished with exit code 0
二、增强for循环
public static void main(String[] args) { List list = new ArrayList(); list.add("a"); list.add("b"); list.add("c"); list.add("d"); for (Object o:list) { System.out.println(o); } }
输出结果:
a b c d Process finished with exit code 0
三、lambda表达式
集合.forEach(临时变量名->{
代码块;
})
public static void main(String[] args) { List aList = new ArrayList(); aList.add("a"); aList.add("b"); aList.add("c"); aList.add("d"); aList.forEach(temp->{ System.out.println(temp); }); }
四、Iterator迭代器
public static void main(String[] args) { List aList = new ArrayList(); aList.add("a"); aList.add("b"); aList.add("c"); aList.add("d"); Iterator iterator = aList.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } }
五、对于List集合,ListIterator
public static void main(String[] args) { List aList = new ArrayList(); aList.add("a"); aList.add("b"); aList.add("c"); aList.add("d"); ListIterator listIterator = aList.listIterator(); while (listIterator.hasNext()){ System.out.println(listIterator.next()); }