Idiomatic way to use for-each loop given an iterator?

后端 未结 9 1607
星月不相逢
星月不相逢 2020-12-03 09:52

When the enhanced for loop (foreach loop) was added to Java, it was made to work with a target of either an array or Iterable.

for ( T item : /*         


        
9条回答
  •  遥遥无期
    2020-12-03 10:24

    What I'd probably do is just make a utility class called Deques which could support this, along with other utilities if desired.

    public class Deques {
      private Deques() {}
    
      public static  Iterable asDescendingIterable(final Deque deque) {
        return new Iterable() {
          public Iterator iterator() {
            return deque.descendingIterator();
          }
        }
      }
    }
    

    This is another case where it's really too bad we don't have lambdas and method references yet. In Java 8, you'll be able to write something like this given that the method reference descendingIterator() matches the signature of Iterable:

    Deque deque = ...
    for (String s : deque::descendingIterator) { ... }
    

提交回复
热议问题