Circular iterator / generator for list of custom class items

Use the index modulo array length:

for( int i = 0; i < K; i++ ) {
   list[ i % list.length ];
}

When it comes to first index (here it's named i) greater or equal to list length, it will "reset" it, because operation modulo (%) returns the remainder after integer division.

The solution does not introduce any classes.


Try this.

static <T> Iterator<T> circularIterator(List<T> list, int count) {
    int size = list.size();
    return new Iterator<T>() {

        int i = 0;

        @Override
        public boolean hasNext() {
            return i < count;
        }

        @Override
        public T next() {
            return list.get(i++ % size);
        }
    };
}

And

List<String> list = Arrays.asList("a", "b", "c");
for (Iterator<String> i = circularIterator(list, 5); i.hasNext();) {
    String s = i.next();
    System.out.println(s);
}

result:

a
b
c
a
b

A simple way to do this is:

import com.google.common.collect.Iterables
import com.google.common.collect.Iterators;

Integer[] arr = {1,2,3,4,5};
Iterator<Integer> iter = Iterators.limit(Iterables.cycle(arr).iterator(),7) ;

Here's a Java 8 friendly way:

IntStream.range(0, K)
    .mapToObj(i -> list[i % list.length])
    .forEach(cc -> /* play with CustomClass cc instance */);