#184 Fluent interface pattern, added cached initialization to anonymous iterator for lazy fluentiterable, small documentation changes

This commit is contained in:
Hannes Pernpeintner 2015-09-03 18:49:52 +02:00
parent a90fcc2391
commit ee47ae021a
3 changed files with 20 additions and 11 deletions

View File

@ -4,7 +4,7 @@ import java.util.Iterator;
/**
* This class is used to realize LazyFluentIterables. It decorates
* a given iterator.
* a given iterator. Does not support consecutive hasNext() calls.
* @param <TYPE>
*/
public abstract class DecoratingIterator<TYPE> implements Iterator<TYPE> {

View File

@ -126,19 +126,14 @@ public class LazyFluentIterable<TYPE> implements FluentIterable<TYPE> {
@Override
public Iterator<TYPE> iterator() {
return new DecoratingIterator<TYPE>(iterable.iterator()) {
int currentIndex = 0;
public int stopIndex;
public int totalElementsCount;
private List<TYPE> list;
private int currentIndex = 0;
@Override
public TYPE computeNext() {
List<TYPE> list = new ArrayList<>();
Iterator<TYPE> newIterator = iterable.iterator();
while(newIterator.hasNext()) {
list.add(newIterator.next());
}
int totalElementsCount = list.size();
int stopIndex = totalElementsCount - count;
initialize();
TYPE candidate = null;
while(currentIndex < stopIndex && fromIterator.hasNext()) {
@ -150,6 +145,19 @@ public class LazyFluentIterable<TYPE> implements FluentIterable<TYPE> {
}
return candidate;
}
private void initialize() {
if(list == null) {
list = new ArrayList<>();
Iterator<TYPE> newIterator = iterable.iterator();
while(newIterator.hasNext()) {
list.add(newIterator.next());
}
totalElementsCount = list.size();
stopIndex = totalElementsCount - count;
}
}
};
}
};

View File

@ -10,6 +10,7 @@ import java.util.function.Predicate;
/**
* This is a simple implementation of the FluentIterable interface. It evaluates
* all chained operations eagerly.
* This implementation would be costly to be utilized in real applications.
* @param <TYPE> the type of the objects the iteration is about
*/
public class SimpleFluentIterable<TYPE> implements FluentIterable<TYPE> {