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

com.patternity.util.LimitedIterator Maven / Gradle / Ivy

Go to download

Extensions of the RestFixture. An extension is a RestFixture with some specific/bespoke behaviour not generic enough to make it to the RestFixture itself.

There is a newer version: 3.1
Show newest version
package com.patternity.util;

import java.util.Iterator;

/**
 * Decorates an iterator such that it only returns the first N elements.
 * 
 * @pattern Decorator target=java.util.Iterator
 *          valueadded="it only returns the first N elements"
 * 
 * @author cyrille martraire
 */
public class LimitedIterator implements Iterator {

    private final Iterator it;
	private final int limit;
	private int count = 0;

    public LimitedIterator(Iterator it, int limit) {
		this.it = it;
		this.limit = limit;
	}

	public boolean hasNext() {
		return count < limit && it.hasNext();
	}

    public T next() {
		count++;
		return it.next();
	}

	/**
	 * To call BEFORE calling next()
	 * 
	 * @return true if the next element is the last that will be returned, so
	 *         that it can be replaced with the ellipsis "..."
	 */
	public boolean isLastElement() {
		return count == limit - 1;
	}

	public void remove() {
		it.remove();
	}

	public String toString() {
		return "LimitedIterator limit=" + limit;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy