如何在Java中迭代一个列表?

The List interface extends Collection interface and stores a sequence of elements. The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list. Unlike sets, list allows duplicate elements, allows multiple null values if null value is allowed in the list.

Java List provides two kinds of iterators using iterator() or listIterator(). First one is forward moving only while listIterator is more flexible, allows both way of navigation, backwards or forwards, allows to modify the list during iterating. In this article, we're discussing both types of iterators to iterate a list using corresponding examples.

Use Iterator

Get iterator from the list to iterate through its elements.

Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
   System.out.print(iterator.next() + " ");
}

使用listIterator

从列表中获取listIterator来遍历其元素。

Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
   System.out.print(iterator.next() + " ");
}

Example 1

以下是一个示例,展示了使用iterator()方法获取一个迭代器来遍历一个列表的示例:

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
      Iterator<Integer> iterator = list.iterator();
     
      while(iterator.hasNext()) {
         System.out.print(iterator.next() + " ");
      }
   }
}

Output

这将产生以下结果 −

1 2 3 4 5

Example 2

以下是一个示例,展示了使用listIterator()方法获取迭代器来迭代一个列表的示例:

package com.tutorialspoint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CollectionsDemo {
   public static void main(String[] args) {
      List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
      Iterator<Integer> iterator = list.listIterator();
     
      while(iterator.hasNext()) {
         System.out.print(iterator.next() + " ");
      }
   }
}

Output

这将产生以下结果 −

1 2 3 4 5

以上就是如何在Java中迭代一个列表?的详细内容,更多请关注其它相关文章!