All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.continual.services.model.core.PagingIterWrapper Maven / Gradle / Ivy

There is a newer version: 0.3.16
Show newest version
package io.continual.services.model.core;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * A simple wrapper for paging through an iterator.  Note that iteration ends when 
 * the original iteration is out of data or a complete page has been delivered.
 * @param 
 */
public class PagingIterWrapper implements Iterator
{
	public PagingIterWrapper ( Iterator iterator, PageRequest pr )
	{
		fIter = iterator;
		fSkipsLeft = pr.getRequestedPage () * pr.getRequestedPageSize ();
		fItemsLeft = pr.getRequestedPageSize ();
	}

	@Override
	public boolean hasNext ()
	{
		initialPageSkip ();
		return fItemsLeft > 0 && fIter.hasNext ();
	}

	@Override
	public T next ()
	{
		if ( !hasNext () )
		{
			throw new NoSuchElementException ();
		}

		initialPageSkip ();
		fItemsLeft--;
		return fIter.next ();
	}

	private final Iterator fIter;
	private int fSkipsLeft;
	private int fItemsLeft;

	private void initialPageSkip ()
	{
		while ( fSkipsLeft > 0 && fIter.hasNext () )
		{
			fSkipsLeft--;
			fIter.next ();	// discard
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy