How to convert a for-loop into a producer?

Denis Kulagin :

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?

Joni :

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();
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=388861&siteId=1