Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

How to Invert an Array in Java

$
0
0

1. Overview

In this quick article, we’ll show how we can invert an array in Java.

We’ll see a few different ways to do this using pure Java 8-based solutions – some of those mutate an existing array and some create a new one.

Next, we’ll look at two solutions using external libraries — one using Apache Commons Lang and one using Google Guava.

2. Defining the Problem

The basic idea is to reverse the order of the elements in the array. So, if given the array:

fruits = {"apples", "tomatoes", "bananas", "guavas", "pineapples"}

We’d like to get:

invertedFruits = {"pineapples", "guavas", "bananas", "tomatoes",  "apples"}

Let’s see some ways we can do that.

3. Using a Traditional for Loop

The first way we might think about to invert an array is by using a for loop:

void invertUsingFor(Object[] array) {
    for (int i = 0; i < array.length / 2; i++) {
        Object temp = array[i];
        array[i] = array[array.length - 1 - i];
        array[array.length - 1 - i] = temp;
    }
}

As we can see, the code iterates through half of the array, changing the elements in symmetric positions.

We use a temporary variable so that we don’t lose the value of the current position of the array during the iteration.

4. Using Java 8 Stream API

We can also invert an array by using the Stream API:

Object[] invertUsingStreams(Object[] array) {
    return IntStream.rangeClosed(1, array.length)
      .mapToObj(i -> array[array.length - i])
      .toArray();
}

Here we use the method IntStream.range to generate a sequential stream of numbers. Then we map this sequence into array indexes in descending order.

5. Using Collections.reverse()

Let’s see how to invert an array using the Collections.reverse() method:

public void invertUsingCollectionsReverse(Object[] array) {
    List<Object> list = Arrays.asList(array);
    Collections.reverse(list);
}

Compared with the previous examples, this is a more readable way to do the task.

6. Using Apache Commons Lang

Another option to invert an array is to use the Apache Commons Lang library. To use it, we must first include the library as a dependency:

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

The latest version of Commons Lang can be found at Maven Central.

Let’s use the ArrayUtils class to invert the array:

public void invertUsingCommonsLang(Object[] array) {
    ArrayUtils.reverse(array);
}

As we can see, this solution is quite simple.

7. Using Google Guava

One more option is to use the Google Guava library. Just as we did with the Commons Lang, we’ll include the library as a dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>22.0</version>
</dependency>

The latest version can be found at Maven Central.

Then, we can use the reverse method in Guava’s Lists class to invert the array:

public Object[] invertUsingGuava(Object[] array) {
    List<Object> list = Arrays.asList(array);
    List<Object> reversed = Lists.reverse(list);
    return reversed.toArray();
}

8. Conclusion

In this article, we looked at several different ways to invert an array in Java. We showed a few solutions using only core Java and two other solutions that use third-party libraries — Commons Lang and Guava.

All the code samples shown here can be found on GitHub — this is a Maven project, so it should be easy to import and run as it is.


Viewing all articles
Browse latest Browse all 4535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>