How to go through the collection without using any loop construct?

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


Recursion ?

Tags:

Java