What are some unique ways in Java to loop through an array?



Occasionally I may include affiliate links, which means I may get a commision if you purchase something via that link. Check out my privacy policy for more info.

This is my answer to this question on Quora.

Kenny Yu mentioned the standard ways to loop through an array. A unique way, I suppose, is to use recursion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static void main(String[] args) {
    int[] array = {4,65,2,34,25,25,43,63,654,635,6};
    loopRecursively(array,0);
}

public static void loopRecursively(int[] array, int i) {
    System.out.println(array[i]);

    i++;

    if(i < array.length) {
        loopRecursively(array, i);
    }
}

However, recursion is well understood. It’s unique in the sense you shouldn’t use it (at least in this case).

Also, although not an array, you can use the forEach method in that is new for Java 8 Lists / Iterables:

1
2
3
List list = Arrays.asList(4,65,2,34,25,25,43,63,654,635,6);

list.forEach(element -> System.out.println(element));

Related posts: