Skip to content

Commit

Permalink
#478 using an stateful iterator implementation to prevent excessive m…
Browse files Browse the repository at this point in the history
…emory consumption on large ranges.
  • Loading branch information
svendiedrichsen committed Dec 3, 2017
1 parent f6f5ec0 commit aed742e
Showing 1 changed file with 22 additions and 17 deletions.
39 changes: 22 additions & 17 deletions src/main/java/org/cactoos/iterable/RangeOf.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,10 @@
*/
package org.cactoos.iterable;

import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.cactoos.Func;
import org.cactoos.func.UncheckedFunc;
import org.cactoos.scalar.StickyScalar;

/**
* Iterable implementation to model range functionality.
Expand All @@ -50,22 +49,28 @@ public class RangeOf<T extends Comparable<T>> extends IterableEnvelope<T> {
}
)
public RangeOf(final T min, final T max, final Func<T, T> incrementor) {
super(
new StickyScalar<>(
() -> {
final UncheckedFunc<T, T> func =
new UncheckedFunc<>(incrementor);
final List<T> values =
new ArrayList<>(0);
T value = min;
while (value.compareTo(max) < 1) {
values.add(value);
value = func.apply(value);
super(() -> new IterableOf<>(
new Iterator<T>() {
private final UncheckedFunc<T, T> inc =
new UncheckedFunc<>(incrementor);
private T value = min;

@Override
public boolean hasNext() {
return this.value.compareTo(max) < 1;
}

@Override
public T next() {
if (!this.hasNext()) {
throw new NoSuchElementException();
}
return values;
final T result = this.value;
this.value = this.inc.apply(this.value);
return result;
}
)
);
}
));
}

/**
Expand Down

0 comments on commit aed742e

Please sign in to comment.