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

Question about java interview. Is there any way in java programming, moreover, it constructs a loop to iterate over a given collection (Array) and works on each element of the collection.

+7
source share
6 answers

Recursion is one way to do this.

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

In addition to recursion, there are utilities in the collection that you can use to create material in the collection. Note that this api also uses internal loop constructs. But the client code will look like this:

 CollectionUtils.forAllDo( yourCollection, new Closure() { void execute(java.lang.Object element) { // do smt with element } } ); 

Check here CollectionUtils: http://commons.apache.org/collections/apidocs/org/apache/commons/collections/Closure.html

+5
source
+3
source

Yes, you can 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); } } 
+2
source

You can change the iterative solution to recursive. Loops are iterative, so just create a recursive solution.

+1
source

Using recursion, we iterate over an array or collection without using a 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); } 
0
source

All Articles