如何使用给定大小的批处理包装Iterator

时间:2018-04-23 05:05:31

标签: java iterator

我有一个实现Iterator接口的对象实例。

如何将它转换为迭代器,每次调用next()时都会返回具有预定义大小(批处理)的对象列表?

Java 8.

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class MyIterator implements Iterator<Integer> {
    @Override
    public boolean hasNext() {
        return 0 <= i && i < x.length;
    }

    @Override
    public Integer next() {
        return x[i++];
    }

    private Integer i = 0;
    private Integer[] x = new Integer[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
}

class MyBatchIterator {
    MyBatchIterator(MyIterator myIterator, int n) {
        this.myIterator = myIterator;
        this.n = n;
    }

    public boolean hasNext() {
        return myIterator.hasNext();
    }

    public List<Integer> next() {
        List<Integer> list = new ArrayList<>(n);
        for (int i = 0; i < n; i++)
            if (myIterator.hasNext()) list.add(myIterator.next());
        return list;
    }

    final MyIterator myIterator;
    final int n;
}

class Main {
    public static void main(String[] args) {
        MyBatchIterator myBatchIterator = new MyBatchIterator(new MyIterator(), 3);
        while (myBatchIterator.hasNext())
            System.out.println(myBatchIterator.next());
    }
}

通用版本:

class MyBatchIterator<E> {
    MyBatchIterator(Iterator<E> iterator,int n) {
        this.iterator=iterator;
        this.n=n;
    }
    public boolean hasNext() {
        return iterator.hasNext();
    }
    public List<E> next() {
        List<E> list=new ArrayList<>(n);
        for(int i=0;i<n;i++)
            if(iterator.hasNext()) list.add(iterator.next());
        return list;
    }
    final Iterator<E> iterator;
    final int n;
}