Home » Core Java » Reverse Array Java Example

About Firouzeh hejazi

Firouzeh hejazi
A self-motivated and hard-working developer with more than 4 years of extensive experience in developing software in java platforms. A multi-skilled and problem-solving engineer who has participated in implementing a range of applications in different roles. Possess a MSc in Knowledge Engineering and Decision Science.

Reverse Array Java Example

ٌHow would you answer this question: how do you reverse an array in Java? 

Well, there are multiple ways to solve this problem:

  • Revere array in Place:You can reverse array by writing your own function, which loops through the array and swaps elements until the array is sorted.
  • You can reverse an array by converting array to ArrayList and then reverse the ArrayList.
  • You can also use Apache Commons ArrayUtils.reverse() method to reverse any array in Java. This method is overloaded to reverse byteshortlongintfloatdouble and String array. You can use any of the method depending upon your array type.

1. Solution 1 – Reverse array Java in Place

This is one of the simplest ways to reverse an array in Java. This algorithm iterate over array and swap elements until you reach the midpoint. This is also known as reversing an array in-place because no additional buffer is used.

In the example above, we used a temp variable to reverse the array, we swap the elements of the array. The first element is swapped with the last element. The second element id swapped with the last but one element and so on.
For instance, consider array [1, 2, 3, …., n-2, n-1, n]. We swap 1 with n, 2 with n-1, 3 with n-2 and further.

reverseExample01
import java.util.Arrays;

public class ArrayReverse {

    public static void main(String[] args) {

        int[] array = {1, 2, 3};
        System.out.println("array before reverse: " + Arrays.toString(array) );

        for(int i=0; i<array.length/2; i++){
            int temp = array[i];
            array[i] = array[array.length -i -1];
            array[array.length -i -1] = temp;
        }

        System.out.println("array after reverse: " + Arrays.toString(array) );
    }
}

The output is:

array before reverse: [1, 2, 3]
array after reverse: [3, 2, 1]

We can do the previous example by using List.add() and List.remove() methods. See the following example:

reverseExample01_2
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayReverse {

    public static void main(String[] args)
    {
        List colors = new ArrayList(
                Arrays.asList("100", "200", "300"));
        System.out.println("Before Reversing: " + colors);

        for (int i = 0, j = colors.size() - 1; i < j; i++) {
            colors.add(i, colors.remove(j));
        }

        System.out.println("After Reversing: " + colors);
    }
}

The output is:

Before Reversing: [100, 200, 300]
After Reversing: [300, 200, 100]

The time complexity of this algorithm is O(n/2) which is O(N) because we are iterating over array till midpoint only.

We can also use recursion to reverse a list in-place as demostrated below:

reverseExample01_3
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayReverse {

    public static void reverseList(List list)
    {
        // base case: list is empty or only one element is left
        if (list == null || list.size() <= 1)
            return;

        // remove first element
        T value = list.remove(0);

        // recur for remaining items
        reverseList(list);

        // insert the top element back after recusing for remaining items
        list.add(value);
    }

    public static void main(String[] args)
    {
        List colors = new ArrayList(
                Arrays.asList("AAA", "BBB", "CCC", "DDD"));

        reverseList(colors);
        System.out.println(colors);
    }
}

The output is:

[DDD, CCC, BBB, AAA]

2. Solution 2 – Using ArrayList

Another simple way to reverse an array in Java is by first converting the array to List and then using Collections.reverse() method which takes a List and reverse the element in linear time.

The Collections.reverse() method has a time complexity of O(n). It runs on linear time because it uses ListIterator of given list It reverses the order of an element in specified list.

This is a typesafe generic method and you can use it to reverse Integer, String, Float or any kind of List in Java. Let’s see an example of reversing a String array in Java:

reverseExample02
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArrayReverse {
    public static void main(String args[])  {

        String[] typesOfInsurance = {"Cat", "Dog", "Elephant"};
        System.out.println("array before reverse: " + Arrays.toString(typesOfInsurance) );
        List listOfProducts = Arrays.asList(typesOfInsurance);
        Collections.reverse(listOfProducts);
        String[] reversed = listOfProducts.toArray(typesOfInsurance);
        System.out.println("array after reverse: " + Arrays.toString(reversed) );
    }
}

The output is:

array before reverse: [Cat, Dog, Elephant]
array after reverse: [Elephant, Dog, Cat]

Note: You cannot reverse an ArrayList using this method if the specified ArrayList or it’s ListIterator doesn’t support set() operation and that’s why you cannot reverse a read only ArrayList because it doesn’t support set() operation. It switches between two algorithms depending upon the size of List or if List implements RandomAccess interface e.g. ArrayList.

If number of elements in List is less than REVERSE_THRESHOLD, which is equal to 18 then it uses for loop for swapping elements otherwise it uses list iterator.

3. Solution 3 – By using ArrayUtils.reverse()

Apache commons lang provides an ArrayUtils class which has overloaded reverse() methods to reverse int, float or object arrays in Java. This method also reverses the given array in place i.e. it doesn’t return a new array.

Create a new Maven project and add the ArrrayReverse class to your project. I have show how to create a Maven project in here.

reverseExample03
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;

public class ArrayReverse {

    public static void main(String args[])  {

        String[] assetClasses = {"Apple", "Banana", "Orange", "Grapes"};
        System.out.println("Array before reversing: " + Arrays.toString(assetClasses));
        ArrayUtils.reverse(assetClasses);
        System.out.println("Array after reversing: " + Arrays.toString(assetClasses));

    }

}

As you can see, apache commons is in red, so ArrayUtils cannot be resolved:

reverse array java - Errors
Errors because of dependency requirement

So we should add the Maven dependecy to pom.xml file:

<dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.1</version>
        </dependency>
</dependencies>

The output is:

Array before reversing: [Apple, Banana, Orange, Grapes]
Array after reversing: [Grapes, Orange, Banana, Apple]

That’s all about how to reverse Array in Java. Usually it’s recommended to use functions from JDK library. Why? because they are well tested for programming bugs and corner cases and they are much more optimized than you think, because of wider audiences who have used and improved them already.

4. Solution 4 – Using Java 8 Stream API

Here we use the method IntStream.rangeClosed to generate a sequential stream of numbers. Then we map this sequence into array indexes in descending order.

reverseExample04
import java.util.Arrays;
import java.util.stream.IntStream;

public class ArrayReverse {

    static Object[] invertUsingStreams(Object[] array) {
        return IntStream.rangeClosed(1, array.length)
                .mapToObj(i -> array[array.length - i])
                .toArray();
    }

    public static void main(String[] args) {
        String[] typesOfInsurance = {"Cherry", "Pineapple", "Melon"};
        System.out.println("array before reverse: " + Arrays.toString(typesOfInsurance) );
        Object[] listOfProducts = invertUsingStreams(typesOfInsurance);
        System.out.println("array after reverse: " + Arrays.toString(listOfProducts) );
    }
}

The output is:

array before reverse: [Cherry, Pineapple, Melon]
array after reverse: [Melon, Pineapple, Cherry]

5. Solution 5 – Using Google Guava

One more option is to use the Google Guava library. Just as we did with the Commons Lang, we’ll include the library as a dependency:

<dependencies>
         <dependency>
             <groupId>com.google.guava</groupId>
             <artifactId>guava</artifactId>
             <version>22.0</version>
         </dependency>
</dependencies>

Now we can use the reverse method in Guava’sLists class to invert the array:

import com.google.common.collect.Lists;

import java.util.Arrays;
import java.util.List;

public class ArrayReverse {

    public static Object[] invertUsingGuava(Object[] array) {
        List list = Arrays.asList(array);
        List reversed = Lists.reverse(list);
        return reversed.toArray();
    }

    public static void main(String[] args) {
        String[] typesOfInsurance = {"John", "Rose", "Peter"};
        System.out.println("array before reverse: " + Arrays.toString(typesOfInsurance) );
        Object[] listOfProducts = invertUsingGuava(typesOfInsurance);
        System.out.println("array after reverse: " + Arrays.toString(listOfProducts) );
    }
}

The output is:

array before reverse: [John, Rose, Peter]
array after reverse: [Peter, Rose, John]

6. Download the Source Code

Download
You can download the full source code of this example here: Reverse Array Java Example
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of