Vijay Shanker Dubey
Vijay Shanker Dubey

Reputation: 4418

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

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.

Upvotes: 7

Views: 1301

Answers (6)

apachauri
apachauri

Reputation: 1

Using recursion we iterate array or collection without using loop. See below recursion method:

public static void iterateArray(int nums[], int index) {

    if (nums.length == index) {

        return;
    }
    System.out.print(nums[index] + " ");
    iterateArray(nums, index + 1);

}

Upvotes: 0

Murat Can ALPAY
Murat Can ALPAY

Reputation: 530

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

Upvotes: 5

Matt
Matt

Reputation: 5684

Yes, you could recursively go through a function to get the same functionality:

public void iterate(int[] array, int index){
    if (index >= array.length){
        return;
    }else{
        //work with element at array[index]
        iterate(array, index+1);
    }
}

Upvotes: 2

Nick
Nick

Reputation: 5805

Recursion is one way to do it

void it(Iterator i) {
    if (i.hasNext()) {
        System.out.println(i.next());
        it(i);
    }
}

Upvotes: 19

jzd
jzd

Reputation: 23629

You can interchange an iterative solution for a recursive one. Loops are iterative, so just create a recursive solution instead.

Upvotes: 1

Simeon
Simeon

Reputation: 7792

Recursion ?

Upvotes: 3

Related Questions