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.lang3.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
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
Latest posts by Wayan (see all)
- How do I install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020