Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 415
Vijay Shanker Dubey Avatar asked Jun 14 '11 13:06

Vijay Shanker Dubey


2 Answers

Recursion is one way to do it

void it(Iterator i) {
    if (i.hasNext()) {
        System.out.println(i.next());
        it(i);
    }
}
like image 135
Nick Avatar answered Nov 12 '22 04:11

Nick


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

like image 31
Murat Can ALPAY Avatar answered Nov 12 '22 04:11

Murat Can ALPAY