# 將迭代器轉換為列表

## 1.概述

``````Iterator<Integer> iterator = Arrays.asList(1, 2, 3).iterator();
``````

## 2.使用While循環

``````List<Integer> actualList = new ArrayList<Integer>();

while (iterator.hasNext()) {

}

assertThat(actualList, containsInAnyOrder(1, 2, 3));
``````

## 3.使用Java 8 `Iterator.forEachRemaining`

``````List<Integer> actualList = new ArrayList<Integer>();

assertThat(actualList, containsInAnyOrder(1, 2, 3));
``````

## 4.使用Java 8 Streams API

``````Iterable<Integer> iterable = () -> iterator;
``````

``````List<Integer> actualList = StreamSupport

.stream(iterable.spliterator(), false)

.collect(Collectors.toList());

assertThat(actualList, containsInAnyOrder(1, 2, 3));``````

## 5.使用番石榴

GoogleGuava庫**提供了創建可變和不可變`List`的選項`,`**因此我們將介紹這兩種方法。

``````List<Integer> actualList = ImmutableList.copyOf(iterator);

assertThat(actualList, containsInAnyOrder(1, 2, 3));``````

``````List<Integer> actualList = Lists.newArrayList(iterator);

assertThat(actualList, containsInAnyOrder(1, 2, 3));``````

## 6.使用Apache Commons

**Apache Commons Collections庫提供了用於`List.`選項`List.`**我們將使用`IteratorUtils`進行轉換：

``````List<Integer> actualList = IteratorUtils.toList(iterator);

assertThat(actualList, containsInAnyOrder(1, 2, 3));``````