Example 1 — A Times Table and an Alternating Pattern
Fill one array with multiples of 7 and another with alternating 1s and 0s.
import java.util.Arrays;
public class ArraysSetAllDemo {
public static void main(String[] args) {
int[] table = new int[10];
Arrays.setAll(table, i -> (i + 1) * 7);
System.out.println("7 times table: " + Arrays.toString(table));
int[] pattern = new int[6];
Arrays.setAll(pattern, i -> i % 2 == 0 ? 1 : 0);
System.out.println("pattern: " + Arrays.toString(pattern));
}
} How It Works
- Index in, value out. The lambda receives 0 to 9; adding 1 before multiplying gives 7 for index 0 and 70 for index 9.
- No loop variable to manage.
setAllvisits every index oftable, so there is noi < table.lengthcondition to get wrong. - Conditions work too.
i % 2 == 0 ? 1 : 0gives 1 at even indexes and 0 at odd ones. - Overload by array type. Both arrays are
int[], so both lambdas are treated asIntUnaryOperator.

