Q:

java- how to logically process n-levels of for loops where n is a variable

In a java program, I am getting some data with each value being assigned a name-
Each data item has a 'level' which is a numeric value.
For level 1, there are 'n' number of values--
the data items have names 
 1-1, 1-2, 1-3.....1-n.

Now, level 2 items have names which are derived from level 1's data items.
So there can be 'm' values of level 2, corresponding to each level 1 item. In the name of each data item, each named section corresponding to a level, is separated from other section of name with a '~'.
For eg, 
    1-1~2-1, 1-1~2-2, 1-1~2-3......1-1~2-m --->level2 corresp. to level 1 item "1-1"
    1-2~2-1, 1-2~2-2, 1-2~2-3, ....1-2~2-m--->level2 corresp. to level 1 item "1-2"

Now, I want to create a function where a parameter is number of levels, and I want to programmatically access all items of that level.
For eg, I can create a for loop within another for loop, to access items of level 2.
But how do I do this for level=x, where x is a variable?

A:

The simplest approach is to use recursion as well as a loop.
public static int count(List list) {
  int sum = 0;
  for(Object o: list) {
     sum += o instanceof List ? count((List) o) : 1;
  }
  return sum;
}

As you can see, this will iterate through every element at every level.

