代码之家  ›  专栏  ›  技术社区  ›  Björn Pollex

是否有一种简单的方法将迭代器复制到Java中的列表中?

  •  7
  • Björn Pollex  · 技术社区  · 15 年前

    我想要这样的东西:

    public void CopyIteratorIntoList(Iterator<Foo> fooIterator) {
        List<Foo> fooList = new ArrayList<Foo>();
        fooList.addAll(fooIterator);
    }
    

    应相当于:

    public void CopyIteratorIntoList(Iterator<Foo> fooIterator) {
        List<Foo> fooList = new ArrayList<Foo>();
        while(fooIterator.hasNext())
            fooList.add(fooIterator.next());
    }
    

    API中是否有实现这一点的方法,或者这是唯一的方法?

    5 回复  |  直到 9 年前
        1
  •  11
  •   Michael Borgwardt    15 年前

    不,在标准API中没有类似的东西。

    在Java中,使用它是不习惯的(因此非常少见)。 Iterator 作为API的一部分,它们通常被生产并立即被消费。

        2
  •  7
  •   Carl    15 年前

    没有,但是 Google Collections library has a nice way to do that (如果您要使用它的某些其他功能-没有理由仅为此添加依赖项):

    Iterators.addAll(targetCollection, sourceIterator);
    
        3
  •  7
  •   Cowan    15 年前

    Guava (谷歌的新通用Java库取代谷歌的集合),这可能是简单的:

    return Lists.newArrayList(fooIterator);
    

    或者如果列表是只读的:

    return ImmutableList.copyOf(fooIterator);
    
        4
  •  3
  •   Stefan Kendall    15 年前

    我不相信迭代器在固定的迭代次数之后会停止,所以这可能不是将数据插入列表的安全方法。考虑一个始终返回常量的伪迭代器实现 42 从呼叫到 next() . 您的应用程序将很快耗尽内存。

        5
  •  1
  •   Adrian    9 年前

    在Java 8中,你可以这样做:

    public void CopyIteratorIntoList(Iterator<Foo> fooIterator) {
        List<Foo> fooList = new ArrayList<Foo>();
        fooIterator.forEachRemaining(fooList::add);
    }
    

    参见: Easy way to change Iterable into Collection