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

后端 未结 9 1616
星月不相逢
星月不相逢 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:17

    The idiomatic way in Java 8 (being a verbose language) is this:

    for (T t : (Iterable) () -> myDeque.descendingIterator()) {
      // use item
    }
    

    I.e. wrap the Iterator in an Iterable lambda. This is pretty much what you did yourself using an anonymous class, but it's a bit nicer with the lambda.

    Of course, you could always just resort to using Iterator.forEachRemaining():

    myDeque.descendingIterator().forEachRemaining(t -> {
      // use item
    });
    

提交回复
热议问题