How do I reverse array elements order?

In this example we are going to use the ArraysUtils helper class from the 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 another type of array such as java.lang.Object, long, int, short, char, byte, double, float and boolean.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayReverseExample {

    public static void main(String[] args) {
        // Define the "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

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

Maven Central

How do I convert an array of primitives into an array of objects?

To convert from primitive arrays into object type arrays, we can use the Apache Commons Lang library. The Commons Lang provides an ArrayUtils class that does this conversion. To convert the other way just use the toPrimitive() method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayPrimitiveObjectConversionDemo {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        boolean[] booleans = {true, false, false, true};
        float[] decimals = {10.1f, 3.14f, 2.17f};

        Integer[] numbersObjects = ArrayUtils.toObject(numbers);
        Boolean[] booleansObjects = ArrayUtils.toObject(booleans);
        Float[] decimalsObjects = ArrayUtils.toObject(decimals);

        numbers = ArrayUtils.toPrimitive(numbersObjects);
        booleans = ArrayUtils.toPrimitive(booleansObjects);
        decimals = ArrayUtils.toPrimitive(decimalsObjects);
    }
}

Maven Dependencies

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

Maven Central