How do I reverse an int array in Java?
To reverse an int array in Java, you can use a loop to swap the elements at the beginning and end of the array, and then move the pointers inward until they meet in the middle of the array.
Here is an example of how you can do this:
int[] array = {1, 2, 3, 4, 5};
int left = 0;
int right = array.length - 1;
while (left < right) {
// swap the elements at the left and right indices
int temp = array[left];
array[left] = array[right];
array[right] = temp;
// move the pointers inward
left++;
right--;
}
System.out.println(Arrays.toString(array)); // [5, 4, 3, 2, 1]
Alternatively, you can use the Collections.reverse
method to reverse the elements of an int
array that has been converted to a List
.
Here is an example of how you can do this:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
int[] array = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.stream(array).boxed().collect(Collectors.toList());
Collections.reverse(list);
int[] reversedArray = list.stream().mapToInt(i -> i).toArray();
System.out.println(Arrays.toString(reversedArray)); // [5, 4, 3, 2, 1]