java - Idiomatic way to use for-each loop given an iterator? -
when enhanced loop (foreach loop) added java, made work target of either array or iterable
.
for ( t item : /*t[] or iterable<? extends t>*/ ) { //use item }
that works great collection classes implement 1 type of iteration, , have single iterator()
method.
but find myself incredibly frustrated odd time want use non-standard iterator collection class. example, trying use deque
lifo/stack print elements in fifo order. forced this:
for (iterator<t> = mydeque.descendingiterator(); it.hasnext(); ) { t item = it.next(); //use item }
i lose advantages of for-each loop. it's not keystrokes. don't exposing iterator if don't have to, since it's easy make mistake of calling it.next()
twice, etc.
now ideally think for-each loop should have accepted iterator
well. doesn't. there idiomatic way of using for-each loop in these circumstances? i'd love hear suggestions use common collections libraries guava.
the best can come in absense of helper method/class is:
for ( t item : new iterable<t>() { public iterator<t> iterator() { return mydeque.descendingiterator(); } } ) { //use item }
which isn't worth using.
i'd love see guava have iterables.wrap
make idiomatic, didn't find that. roll own iterator wrapper via class or helper method. other ideas?
edit: side-note, can give valid reason why enhanced for-loop shouldn't have been able accept iterator
? go long way making me live current design.
what i'd make utility class called deques
support this, along other utilities if desired.
public class deques { private deques() {} public static <t> iterable<t> asdescendingiterable(final deque<t> deque) { return new iterable<t>() { public iterator<t> iterator() { return deque.descendingiterator(); } } } }
this case it's bad don't have lambdas , method references yet. in java 8, you'll able write given method reference descendingiterator()
matches signature of iterable
:
deque<string> deque = ... (string s : deque::descendingiterator) { ... }
Comments
Post a Comment