在java中,有各种迭代List集合的技术,我们可用来迭代List集合,以下是常用的几种方法:
- 使用基本for循环(等同于/ do-while)
- 使用for-each循环
- 使用Iterator
- 使用ListIterator
- 使用Stream(在Java8中引入)
示例1
文件:IterateListExample.java –
import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class IterateListExample { public static void main(String[] args) { List<Integer> numbers=Arrays.asList(new Integer[]{12345}); /* Basic for Loop*/ System.out.print("Basic For Loop : "); for (int i = 0; i < numbers.size(); i++) { System.out.print(numbers.get(i)+" "); } /* For-Each loop */ System.out.print(" For-Each Loop : "); for (Integer integer : numbers) { System.out.print(integer+" "); } /* Using Iterator */ System.out.print(" Using Iterator : "); for (Iterator<Integer> iterator = numbers.iterator(); iterator.hasNext();) { System.out.print(iterator.next()+" "); } /* Using ListIterator */ System.out.print(" Using ListIterator : "); for (ListIterator<Integer> listIterator=numbers.listIterator();listIterator.hasNext();) { System.out.print(listIterator.next()+" "); } /* Using Stream */ System.out.print(" Using Stream : "); numbers.stream().forEach(e->System.out.print(e+" ")); } }
执行上面示例代码,得到以下结果 –
Basic For Loop : 1 2 3 4 5 For-Each Loop : 1 2 3 4 5 Using Iterator : 1 2 3 4 5 Using ListIterator : 1 2 3 4 5 Using Stream : 1 2 3 4 5
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264155.html