Reputation: 4418
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
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
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
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
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
Reputation: 23629
You can interchange an iterative solution for a recursive one. Loops are iterative, so just create a recursive solution instead.
Upvotes: 1