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.

The ArrayUtils.reverse() method is overloaded so we can reverse other types of array such as java.lang.Object, long, int, short, char, byte, double, float and boolean.

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. 
        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}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-lang/commons-lang/2.6/commons-lang-2.6.jar -->
<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA. Support me by donating >> here <<.

Leave a Reply