How to convert a for-loop into a producer?

萝らか妹 提交于 2021-01-29 13:16:39

问题


There is a SynchronousProducer interface, that supports two operations:

public interface SynchronousProducer<ITEM> {
    /**
     * Produces the next item.
     *
     * @return produced item
     */
    ITEM next();

    /**
     * Tells if there are more items available.
     *
     * @return true if there is more items, false otherwise
     */
    boolean hasNext();
}

Consumer asks the producer if there are more items available and if none goes into a shutdown sequence.

Now follows the issue.

At the moment there is a for-loop cycle that acts as a producer:

for (ITEM item: items) {
  consumer.consume(item);
}

The task is to convert a controlling code into the following:

while (producer.hasNext()) {
  consumer.consume(producer.next())
}

consumer.shutdown();

The question. Given the items: how to write the producer implementing SynchronousProducer interface and duplicating the logic of the for-loop shown above?


回答1:


If items implements Iterable, you can adapt it to your SynchronousProducer interface like this:

class IterableProducer<T> implements SynchronousProducer<T> {

    private Iterator<T> iterator;

    public IterableProducer(Iterable<T> iterable) {
        iterator = iterable.iterator();
    }

    @Override
    public T next() {
        return iterator.next();
    }

    @Override
    public boolean hasNext() {
        return iterator.hasNext();
    }
}


来源:https://stackoverflow.com/questions/60994150/how-to-convert-a-for-loop-into-a-producer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!