Skip to content

Commit ee47ae0

Browse files
committed
iluwatar#184 Fluent interface pattern, added cached initialization to anonymous iterator for lazy fluentiterable, small documentation changes
1 parent a90fcc2 commit ee47ae0

File tree

3 files changed

+20
-11
lines changed

3 files changed

+20
-11
lines changed

fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/DecoratingIterator.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
/**
66
* This class is used to realize LazyFluentIterables. It decorates
7-
* a given iterator.
7+
* a given iterator. Does not support consecutive hasNext() calls.
88
* @param <TYPE>
99
*/
1010
public abstract class DecoratingIterator<TYPE> implements Iterator<TYPE> {

fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/lazy/LazyFluentIterable.java

+18-10
Original file line numberDiff line numberDiff line change
@@ -126,19 +126,14 @@ public FluentIterable<TYPE> last(int count) {return new LazyFluentIterable<TYPE>
126126
@Override
127127
public Iterator<TYPE> iterator() {
128128
return new DecoratingIterator<TYPE>(iterable.iterator()) {
129-
int currentIndex = 0;
129+
public int stopIndex;
130+
public int totalElementsCount;
131+
private List<TYPE> list;
132+
private int currentIndex = 0;
130133

131134
@Override
132135
public TYPE computeNext() {
133-
List<TYPE> list = new ArrayList<>();
134-
135-
Iterator<TYPE> newIterator = iterable.iterator();
136-
while(newIterator.hasNext()) {
137-
list.add(newIterator.next());
138-
}
139-
140-
int totalElementsCount = list.size();
141-
int stopIndex = totalElementsCount - count;
136+
initialize();
142137

143138
TYPE candidate = null;
144139
while(currentIndex < stopIndex && fromIterator.hasNext()) {
@@ -150,6 +145,19 @@ public TYPE computeNext() {
150145
}
151146
return candidate;
152147
}
148+
149+
private void initialize() {
150+
if(list == null) {
151+
list = new ArrayList<>();
152+
Iterator<TYPE> newIterator = iterable.iterator();
153+
while(newIterator.hasNext()) {
154+
list.add(newIterator.next());
155+
}
156+
157+
totalElementsCount = list.size();
158+
stopIndex = totalElementsCount - count;
159+
}
160+
}
153161
};
154162
}
155163
};

fluentinterface/src/main/java/com/iluwatar/fluentinterface/fluentiterable/simple/SimpleFluentIterable.java

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
/**
1111
* This is a simple implementation of the FluentIterable interface. It evaluates
1212
* all chained operations eagerly.
13+
* This implementation would be costly to be utilized in real applications.
1314
* @param <TYPE> the type of the objects the iteration is about
1415
*/
1516
public class SimpleFluentIterable<TYPE> implements FluentIterable<TYPE> {

0 commit comments

Comments
 (0)