How do I reverse array elements order?

In this example we are going to use the ArraysUtils helper class from Apache Commons Lang library to reverse the order of array elements. The method to reverse the order of array elements is ArrayUtils.reverse() method.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.ArrayUtils;

public class ArrayReverseExample {

    public static void main(String[] args) {
        //
        // Define colors array.
        //
        String[] colors = {"Red", "Green", "Blue", "Cyan", "Yellow", "Magenta"};
        System.out.println(ArrayUtils.toString(colors));

        //
        // Now we reverse the order of array elements using the ArrayUtils.reverse()
        // method. The reverse method is overloaded so we can reverse other type
        // of array such as boolean, char, byte, double, etc.
        //
        ArrayUtils.reverse(colors);
        System.out.println(ArrayUtils.toString(colors));
    }
}

Here is the output of the code snippet above:

{Red,Green,Blue,Cyan,Yellow,Magenta}
{Magenta,Yellow,Cyan,Blue,Green,Red}

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply