A java interview question. Is there any way in java programming other then the loop constructs to iterate through a given collection(an Array) and work on the each element of the collection.
Recursion is one way to do it
void it(Iterator i) {
    if (i.hasNext()) {
        System.out.println(i.next());
        it(i);
    }
}
                        Other than recursion commons-collection has utility methods that you may use to do stuff on a collection. Note that this api also uses loop constructs internally. But the client code would look like :
CollectionUtils.forAllDo(
   yourCollection,
   new Closure() {
      void execute(java.lang.Object element) {
      // do smt with element
      }
   }
);
Check the CollectionUtils here : http://commons.apache.org/collections/apidocs/org/apache/commons/collections/Closure.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With