Iterator to list的三种方法
文章目錄
- 簡介
- 使用while
- 使用ForEachRemaining
- 使用stream
- 總結
Iterator to list的三種方法
簡介
集合的變量少不了使用Iterator,從集合Iterator非常簡單,直接調用Iterator方法就可以了。
那么如何從Iterator反過來生成List呢?今天教大家三個方法。
使用while
最簡單最基本的邏輯就是使用while來遍歷這個Iterator,在遍歷的過程中將Iterator中的元素添加到新建的List中去。
如下面的代碼所示:
@Testpublic 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的方法:
@Testpublic 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
更多精彩內容且看:
- 區塊鏈從入門到放棄系列教程-涵蓋密碼學,超級賬本,以太坊,Libra,比特幣等持續更新
- Spring Boot 2.X系列教程:七天從無到有掌握Spring Boot-持續更新
- Spring 5.X系列教程:滿足你對Spring5的一切想象-持續更新
- java程序員從小工到專家成神之路(2020版)-持續更新中,附詳細文章教程
歡迎關注我的公眾號:程序那些事,更多精彩等著您!
更多內容請訪問 www.flydean.com
總結
以上是生活随笔為你收集整理的Iterator to list的三种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: fail-safe fail-fast知
- 下一篇: Copy ArrayList的四种方式