Core Java

Reverse Elements Of Java Array

Overview:

In this quick tutorial, we’ll learn ways in which we can invert or reverse an array. We’ll first look at the most basic Java implementations and later cover a few third-party options.

Problem Definition:

Consider we have an array of elements:

Our problem is to be able to invert or reverse the elements of an array so that our outputArr would look like:

Also, we’ll try to make a generic solution that will work for all array types. So, let’s get started!

Plain-Java Implementations:

1.) for-Loop

An old-school way of reversing array elements would involve swapping the elements until we iterate and reach the mid element in the array.

Here, we have inverted the array with no extra space except for a temporary variable. Also, it’s pretty efficient as we are iterating only until we reach the mid element in the array.

2.) Java 8 Streams API

We can also invert our array using Java 8 Streams API:

This approach is not pretty intuitive. Here, we generated a stream of integers and then mapped them as array indexes of the elements in the reverse order.

3.) java.util.Collections

Collections class has a reverse() method which can reverse elements of say a List or any other collection.   We can use it to our advantage by first converting our array into a List. Once we have reversed its elements, we can again convert that reversed list into an array.

This code looks more readable and intuitive than the one using Streams API.

 

Third-Party Libraries:

1.) Apache Commons Lang

ArrayUtils class in the Apache Commons Lang library provides a reverse() method which can serve our purpose.

This is a pretty cool and quick way to reverse our array. All we need to make sure is to have the dependency of the library in our POM:

The latest version is easily available at Maven Central.

2.) Google Guava

Google Guava’s library has a method to reverse a List which is another option that we can opt for. Our code would look similar to:

Also, we must make sure that we include the library dependency in our POM:

The latest version can be looked out at Maven Central.

Conclusion:

In this short tutorial, we learned to solve the basic problem of reversing an array. I hope that helps!

There’s an article Java Code Geeks-Arrays that I recommend checking out to know about Java arrays in general.

Be the First to comment.

Leave a Comment

Your email address will not be published. Required fields are marked *