Now that we have aggregate operations, is there still any use for iterators? What cases?
Asked
Active
Viewed 83 times
2
-
How would you use aggregate operators in place of an iterator? – Anubian Noob May 18 '14 at 07:13
1 Answers
1
Iterator
may be usefull when its hasNext()
function needs to be called more than once, making something different when processing the last element of the collection:
while (iter.hasNext()) {
print(iter.next);
if (iter.hasNext())
print(',');
else
print('.');
}
(comma separated items, dot at the end). This seems generally the case when certain action is required between the two iterations, but not before the first iteration and not after the last iteration.
for
loop with check if this is the last index seem much more clumsy. Guava provides methods to join lists but printing with commas may not be the only case where it is required to process the last element differently. Creating a sublist and then handling the last element outside the loop also seems less readable.

Audrius Meškauskas
- 20,936
- 12
- 75
- 93