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

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

    I suggest to create a helper class with factory methods that you can use like this:

    import static Iter.*;
    
    for( Element i : iter(elements) ) {
    }
    
    for( Element i : iter(o, Element.class) ) {
    }
    

    As a next step, the return type of iter() could be a fluent interface so you can do:

    for( Element i : iter(elements).reverse() ) {
    }
    

    or maybe

    for( Element i : reverse(elements) ) {
    }
    

    You should also have a look at op4j which solves many of these problems with a very nice API.

提交回复
热议问题