Fetch your java.util.List’s next element and restart from the first element automatically, when no more elements left available.
Code
package util;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
public class NextValCyclicFetcher<T> {
private List<T> list;
private Iterator<T> iterator;
public NextValCyclicFetcher(List<T> list) {
if (null == list) {
throw new IllegalArgumentException("null");
}
if (list.isEmpty()) {
throw new IllegalArgumentException("empty");
}
this.list = list.stream().collect(Collectors.toList());
this.iterator = this.list.iterator();
}
public T next() {
if (iterator.hasNext()) {
return iterator.next();
}
iterator = list.iterator();
return next();
}
}
It uses standard Java 8 imports.
The passed in List is copied so that if the original list is modified outside the cyclic fetcher, the cyclic fetcher will continue working as expected.
Example
public void exampleMethod() {
List<String> list = Arrays.asList("first", "second", "third");
NextValCyclicFetcher<String> listCyclicFetcher = new NextValCyclicFetcher<>(list);
// more code
while (condition) {
String string = listCyclicFetcher.next();
System.out.println(string);
}
}
Output
first
second
third
first
second
third
first
...
(Until condition is not satisfied anymore)