How do I reverse the order of array elements?

In this code snippet you’ll learn how to reverse the order of array elements. To reverse to element order will be using the Collections.reverse() method. This method requires an argument with List type. Because of this we need to convert the array to a List type first. We can use the Arrays.asList() to do the conversion. And then we reverse it. To convert the List back to array we can use the Collection.toArray() method.

Let’s see the code snippet below:

package org.kodejava.example.util;

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

public class ArrayReverse {
    public static void main(String[] args) {
        // Creates an array of Integers and print it out.
        Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8};
        System.out.println("Arrays.toString(numbers) = " + Arrays.toString(numbers));

        // Convert the int arrays into a List.
        List numberList = Arrays.asList(numbers);

        // Reverse the order of the List.

        // Convert the List back to arrays of Integers
        // and print it out.
        System.out.println("Arrays.toString(numbers) = " + Arrays.toString(numbers));

The output of the code snippet above is:

Arrays.toString(numbers) = [0, 1, 2, 3, 4, 5, 6, 7, 8]
Arrays.toString(numbers) = [8, 7, 6, 5, 4, 3, 2, 1, 0]

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.