Iterator to list的三種方法
簡介
集合的變量少不了使用Iterator,從集合Iterator非常簡單,直接調用Iterator方法就可以了。
那么如何從Iterator反過來生成List呢?今天教大家三個方法。
使用while
最簡單最基本的邏輯就是使用while來遍歷這個Iterator,在遍歷的過程中將Iterator中的元素添加到新建的List中去。
如下面的代碼所示:
@Test
public void useWhile(){
List<String> stringList= new ArrayList<>();
Iterator<String> stringIterator= Arrays.asList("a","b","c").iterator();
while(stringIterator.hasNext()){
stringList.add(stringIterator.next());
}
log.info("{}",stringList);
}
使用ForEachRemaining
Iterator接口有個default方法:
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
實際上這方法的底層就是封裝了while循環,那么我們可以直接使用這個ForEachRemaining的方法:
@Test
public void useForEachRemaining(){
List<String> stringList= new ArrayList<>();
Iterator<String> stringIterator= Arrays.asList("a","b","c").iterator();
stringIterator.forEachRemaining(stringList::add);
log.info("{}",stringList);
}
使用stream
我們知道構建Stream的時候,可以調用StreamSupport的stream方法:
public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel)
該方法傳入一個spliterator參數。而Iterable接口正好有一個spliterator()的方法:
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
那么我們可以將Iterator轉換為Iterable,然后傳入stream。
仔細研究Iterable接口可以發現,Iterable是一個FunctionalInterface,只需要實現下面的接口就行了:
Iterator<T> iterator();
利用lambda表達式,我們可以方便的將Iterator轉換為Iterable:
Iterator<String> stringIterator= Arrays.asList("a","b","c").iterator();
Iterable<String> stringIterable = () -> stringIterator;
最后將其換行成為List:
List<String> stringList= StreamSupport.stream(stringIterable.spliterator(),false).collect(Collectors.toList());
log.info("{}",stringList);
總結
三個例子講完了。大家可以參考代碼https://github.com/ddean2009/learn-java-collections
歡迎關注我的公眾號:程序那些事,更多精彩等着您!
更多內容請訪問 www.flydean.com