Added a new iterator utility for counting.
@@ -114,6 +114,23 @@ public final class IteratorUtils {
};
}
+ public static Iterator<Integer> count(int amount) {
+ return count(0, amount);
+ }
+
+ public static Iterator<Integer> count(int start, int amount) {
+ assert(amount >= 0);
+ return new CountingIterator(start, amount);
+ }
+
+ public interface MapFunction<T, S> {
+ public S map(T value);
+ }
+
+ public interface FilterFunction<T> {
+ public boolean keep(T value);
+ }
+
private static class MapIterable<T, S> implements Iterable<S> {
private Iterable<T> baseIterable;
private MapFunction<T, S> mapFunction;
@@ -174,10 +191,6 @@ public final class IteratorUtils {
}
}
- public interface MapFunction<T, S> {
- public S map(T value);
- }
-
private static class FilterIterable<T> implements Iterable<T> {
private Iterable<T> baseIterable;
private FilterFunction<T> filter;
@@ -239,10 +252,6 @@ public final class IteratorUtils {
}
}
- public interface FilterFunction<T> {
- public boolean keep(T value);
- }
-
private static class ConcatenationIterable<T> implements Iterable<T> {
private Iterable<? extends T>[] collections;
@@ -362,6 +371,36 @@ public final class IteratorUtils {
}
}
+ private static class CountingIterator implements Iterator<Integer> {
+ private final int end;
+
+ private int next;
+
+ public CountingIterator(int start, int count) {
+ next = start;
+ end = start + count;
+ }
+
+ @Override
+ public Integer next() {
+ if (!hasNext()) {
+ throw new java.util.NoSuchElementException();
+ }
+
+ return Integer.valueOf(next++);
+ }
+
+ @Override
+ public boolean hasNext() {
+ return next < end;
+ }
+
+ @Override
+ public void remove() {
+ throw new UnsupportedOperationException();
+ }
+ }
+
// Taken from: https://stackoverflow.com/a/11916946
// TODO(eriq): This could use a lot of cleanup.
private static class PermutationIterator implements Iterator<int[]> {
