The easiest way would be to use a switch and the modulus operator on the loop index. For example:
public class Main {
static void f1() {
System.out.println("f1");
}
static void f2() {
System.out.println("f2");
}
static void f3() {
System.out.println("f3");
}
static void f4() {
System.out.println("f4");
}
public static void main(String[] args) {
for (int i = 0; i < 16; ++i) {
switch (i % 4) {
case 0:
f1();
break;
case 1:
f2();
break;
case 2:
f3();
break;
case 3:
f4();
break;
}
}
}
}
As @Andreas points out, once you remember the right type to use for the function (Runnable
in this case), this can be done with an array:
// ...
static Runnable[] functions =
{ Main::f1, Main::f2, Main::f3, Main::f4 };
public static void main(String[] args) {
for (int i = 0; i < 16; ++i)
functions[i % 4].run();
}
Runnable
isn't really consistent with Callable
so this seems like a bit of a mis-use, but I don't see a simple way to do this via types in java.util.function
.