title: Design Pattern for Iterator with Pagination with Java
body: <p>I'm attempting to make service calls to an API that returns back results in a paged format and want suggestions on the design pattern for the iterator for this. </p>
  
  <p>What I have till now is something like this</p>
  
  <pre><code>public class CustomIterator implements Iterator&lt;Type&gt; {
  
   private List&lt;Result&gt; results;
   private Service service;
  
   private int index;
   private int paginatedResultSize;
   private int totalResultsSize;
  
   public CustomIterator(Service service) {
    this.service = service;
    this.index = 0;
    this.results = getResults(index);
    this.totalResultsSize = this.results.totalResultsSize();
   }
  
   @Override
   public boolean hasNext() {
     if (index &lt; totalResultsSize)
      return true;
     return false;
   }
  
   @Override
   public Type next() {
  
    if(index == paginatedResultSize) {
     getResults(index);
    }
  
    return results[index++];
  
   }
  
   private List&lt;Result&gt; getResults(index) throws Exception {
    this.results = service.makeServiceCall(index);
    this.paginatedResultSize = this.results.size();
    return this.results;
   }
  
  }
  </code></pre>
  
  <p>Now, I understand that the purpose of the iterator is normally to just iterate, but I also want to encapsulate the whole pagination into a separate area so my client class can just call .next() on the class and get all values without having to know about the internal pagination details. Is there a clean pattern to getting this done?</p>
  
  <p>With this the first issue I ran into was that the service call was throwing a checked exception and next() obviously does not.</p>
  
  <p>Some options I noticed on the internet were to have this throw a RunTimeException which I'd rather only do as a last resort since I like checked exceptions for service calls. My gut feeling is that the service call should be done in a separate layer completely, but I'm not sure how the iterator will work with that pagination there. Any suggestions/links appreciated.</p>