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)

By horaz

Hello, my name is Horacio Conde, Vic’s proud father, an apprentice maker and a computer science engineer. I live in Mexico City and I’ve been working professionally in software development for more than fifteen years now. I’m very interested in technologies such as programming, The Internet of Things (IoT) (Arduino, Raspberry Pi), electronics, physical computing, automation, woodworking.

Leave a Reply

Your email address will not be published. Required fields are marked *