Initialize all elements of an array with a specific value in Java
This post will discuss how to initialize all array elements with a specified value in Java.
We know that an array is initialized with a default value on creation. The default value is 0 for integral types. If we need to initialize an array with a different value, we can use any of the following methods:
1. Using Arrays.fill() method
The most common approach is to use the Arrays.fill() method, which internally uses a for-loop.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Arrays; class Main { public static void main(String[] args) { int size = 5; int val = 1; Integer[] arr = new Integer[size]; Arrays.fill(arr, val); System.out.println(Arrays.toString(arr)); } } |
2. Using Collections.nCopies() method
Here, the idea is to call the Collections.nCopies() method to get a list and then convert it to an array using the List.toArray() method.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Arrays; import java.util.Collections; class Main { public static void main(String[] args) { int size = 5; int val = 1; Integer[] arr = Collections.nCopies(size, val) .toArray(new Integer[0]); System.out.println(Arrays.toString(arr)); } } |
3. Using Arrays.setAll() method
Another alternative is to use the setAll() method of the Arrays class. It sets all elements of the specified array with the help of a generator method that accepts an index and generates a corresponding value for that index. We can easily set a specific value for each array element by returning the same value for every index.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.Arrays; class Main { public static void main(String[] args) { int size = 5; int val = 1; Integer[] arr = new Integer[size]; Arrays.setAll(arr, i -> val); System.out.println(Arrays.toString(arr)); } } |
4. Using Java 8
In Java 8 and above, we can use Stream, which offers many alternatives, as shown below:
|
1 2 3 |
Integer[] arr = IntStream.of(new int[size]) .mapToObj(i -> val) .toArray(Integer[]::new); |
|
1 2 3 4 |
Integer[] arr = IntStream.generate(() -> val) .limit(size) .mapToObj(i -> val) .toArray(Integer[]::new); |
|
1 2 3 |
Integer[] arr = Arrays.stream(new Integer[size]) // or, use Stream.of() .map(e -> val) .toArray(Integer[]::new); |
|
1 2 3 4 |
Integer[] arr = Stream.generate(String::new) .limit(size) .map(s -> val) .toArray(Integer[]::new); |
That’s all about initializing all array elements with a specified value in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)