天天看點

Iterator to list的三種方法

目錄

  • ​​簡介​​
  • ​​使用while​​
  • ​​使用ForEachRemaining​​
  • ​​使用stream​​
  • ​​總結​​

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​​