'Fill an array with descending values
Trying to find the easiest way to fill an array with some values starting at 23 in descending order. I have the code below but not getting the result i am looking for:
int[] arr = new int[8];
int i = 24;
Arrays.fill(arr, --i);
System.out.println(Arrays.toString(arr));
output now
[23, 23, 23, 23, 23, 23, 23, 23]
expected
[23, 22, 21, 20, 19, 18, 17, 16]
How to fill an array easily and get the expected output, if possible without a for/while loop?
Solution 1:[1]
Why not simply use a for loop?
for (int j = 0; j < arr.length; j++) {
arr[j] = i;
i--;
}
You can also use the Arrays.setAll function
Arrays.setAll(arr, (index) -> i - index);
By the way, Arrays.fill will fill the all array with the given value, so that's why you're getting [23, 23, 23, 23, 23, 23, 23, 23].
Solution 2:[2]
You could use Streams :
IntStream.iterate(23, i -> i - 1)
.limit(8)
.toArray();
Solution 3:[3]
You'll need to write a for loop in descending order to complete and display the array.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Vladimir Stanciu |
| Solution 3 | Jamil Matheny |
