## DEV Community is a community of 660,470 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Reverse An Array - 3 Methods

Amritanshu Dev Rawat
New Gen Developer
• Method 1 - Revere with For Loop and print
``````public class ReverseArray {
public static void main(String[] args) {
// Array with some element
int[] myArray = {10,22,33,11,88,9,2};
// reverse loop and printing
for(int i = myArray.length-1;i>=0;i--) {
System.out.print(myArray[i]+ " ");
}
}
}
``````
• Method 2 - Using Array List
``````// Method 2 Reverse an array using array list
public class ReverseArray {
public static void main(String[] args) {
// Array List
ArrayList<Integer> myArray = new ArrayList<Integer>();

// reverse array and method
Collections.reverse(myArray);
System.out.println(myArray);
}
}
``````
• Method 3 - Two Pointers and Swap
``````// Method 3 Reverse with swap
public class ReverseArray {
public static void main(String[] args) {

// Array with some element
int[] myArray = {10,22,33,11,88,9,2};

int start = 0;
int end = myArray.length-1;
int temp = 0;

// looping and swapping
while(end>start) {
temp = myArray[start];
myArray[start] = myArray[end];
myArray[end] = temp;
end--;
start++;
}

for(int i:myArray) {
System.out.print(i+" ");
}
}
}
``````

## Discussion (5)

Alex Lohr

This seems to be C++, not JavaScript. In JavaScript, you'd have

``````const myArray = [10,22,33,11,88,9,2]

// native (will change the original reference)
myArray.reverse()
console.log(myArray)

myArray.reverse() // change it back

// functional
const functionalReversedMyArray = myArray.reduce((result, item) => [item, ...result], [])
console.log(functionalReversedMyArray)

// imperative
const imperativeReversedMyArray = []
for (const index in myArray) {
imperativeReversedMyArray.unshift(myArray[index])
}
console.log(imperativeReversedMyArray)

// recursive
const recursiveArrayReversal = (inputArray, partiallyReversed = []) =>
inputArray.length
? recursiveArrayReversal(inputArray.slice(1), [inputArray[0], ...partiallyReversed])
: partiallyReversed
const recursiveReversedMyArray = recursiveArrayReversal(myArray)
console.log(recursiveReversedMyArray)
``````
Amritanshu Dev Rawat

Thanks :) That was JAVA :)

Davis Tibbz • Edited

Here is a crazy one 😀:

``````public static int[] reverse(int[] array) {
return IntStream.range(0, array.length).map(i -> array[array.length - 1 - i]).toArray();
}
public static void main(String[] args) {
//integer array 'a'
var a = reverse(new int[]{2, 4, 5, 6, 7, 8});
System.out.println(Arrays.toString(a));
}
``````
June July

Great work bro!

Amritanshu Dev Rawat

:) thanks