Reverse order array in java

Reverse an Array in Java

Learn how to reverse or invert an array in Java. A reversed array is of equal size to the original array and contains the same items but in the reverse order.

String[] array = ; String[] reveresedArray = ;

The easiest way to reverse the array is to use the existing APIs built for this very purpose. Collections.reverse() method is such an API. This method reverses the elements in a list, so we must convert the array into a list first by using java.util.Arrays.asList(array) and then reverse the list. It will reverse the backing array items as well.

Note that the reverse() method reverses the order of the items in the original array. So if you want to keep the original array unchanged, consider cloning the array first.

String[] array = ; Collections.reverse(Arrays.asList(array)); System.out.println(Arrays.toString(array)); //[E, D, C, B, A]

Warning: Note that reverse() API does not work with primitive arrays because Arrays.asList(intArray) will return a List whose only element is the original array. Thus there is nothing to reverse.

int[] array = ; Collections.reverse(Arrays.asList(array)); //Does not reverses the array

2. Swapping Array Elements in For Loop

Another simple and straightforward way is to iterate through the array swapping them from the beginning position with the elements in the last position.

For example, the given image describes the swapping process where we have an array of 5 elements.

  • In the first iteration, we swap the first and last elements.
  • In the second iteration, we swap the second and second-last elements.
  • The same swapping goes on in the for-loop until we hit the middle of the array, at this time the array has been reversed.

String[] array = ; for (int i = 0; i < array.length / 2; i++) < String temp = array[i]; array[i] = array[array.length - 1 - i]; array[array.length - 1 - i] = temp; >System.out.println(Arrays.toString(array)); //[E, D, C, B, A]

3. Reversing Array Using Stream API

In this approach, we will use read the array elements in reverse starting from last position, and then we will store all the elements in a new array.

The original array remains unchanged in this approach.

final String[] arr = new String[]; Object[] reversedArr = IntStream.rangeClosed(1, array.length) .mapToObj(i -> arr[arr.length - i]) .toArray(); System.out.println(Arrays.toString(reversedArr)); //[E, D, C, B, A]

If our application has an existing dependency on Apache Commons Lang library then it has an excellent and direct API to reverse any kind of array.

String[] array = ; ArrayUtils.reverse(arr); System.out.println(Arrays.toString(arr)); //[E, D, C, B, A]

In this short tutorial, we learned to reverse an array using different techniques. We learned to use for-loop, swapping items, Collections API and also the Apache Commons’s ArrayUtils class.

In any of the approaches, if you want to keep the original array unchanged, clone the array first and then apply the reverse logic to it.

Источник

How to Reverse Array in Java

If you are looking for how to reverse an array in Java, then this article is just written for you, keep reading until the end.

As we know, arrays are one of the most used data structures for storing multiple values in a single variable.

So, we are going to explore different ways to invert the order of an array’s values using Java core methods and external libraries.

Reverse Array Using Java 7

Java 7 provides several approaches to invert an array. Let’s go down the rabbit hole and take a close look at each approach.

Using Swapping Approach

To reverse the order of an array’s elements, we can simply use a traditional for loop.

First, we need to iterate over the given array. Then, we alternate the element at the index i with the element at the index arrayLength — i — 1 until we reach the middle of the array.

Reverse Array in Java using Swapping

Now, let’s see how to implement this in Java:

 @Test public void reverseArrayUsingSwapping() < String[] initialArray = < "A", "B", "C", "D", "E", "F" >; for (int i = 0; i < initialArray.length / 2; i++) < String temp = initialArray[i]; initialArray[i] = initialArray[initialArray.length - i - 1]; initialArray[initialArray.length - i - 1] = temp; >String[] reversedArray = < "F", "E", "D", "C", "B", "A" >; assertArrayEquals(reversedArray, initialArray); > 

Using Copying Approach

Here, we will use the for loop as well, but with a different logic.

The basic idea is to use another array that acts as a copy of the initial array. However, we need to copy the elements in reverse order.

Now, let’s illustrate this using a practical example:

 @Test public void reverseArrayUsingCopying() < String[] initialArray = < "A", "B", "C", "D", "E", "F" >; String[] result = new String[initialArray.length]; for (int i = 0; i < initialArray.length; i++) < result[i] = initialArray[initialArray.length - i - 1]; >String[] reversedArray = < "F", "E", "D", "C", "B", "A" >; assertArrayEquals(reversedArray, result); > 

Please note that we can’t use the enhanced for loop to iterate through an array backward.

Using Collections.reverse() Method

Collections is a utility class that comes with multiple ready-to-use static methods for operating and manipulating collections.

Among these methods, we find the reverse() method. It was introduced with the aim of reversing a collection of elements.

 @Test public void reverseArrayUsingCollections() < String[] initialArray = < "A", "B", "C", "D", "E", "F" >; Collections.reverse(Arrays.asList(initialArray)); String[] reversedArray = < "F", "E", "D", "C", "B", "A" >; assertArrayEquals(reversedArray, initialArray); > 

Please note that the method accepts a list and not an array. This is why we used the Arrays.asList() method.

Array in Reverse Order Using Java 8

The Java 8 stream API provides another convenient way to reverse the order of the elements in a particular array.

So, let’s exemplify this using a test case:

 @Test public void reverseArrayUsingStreamApi() < int[] initialArray = < 1, 9, 5, 8, 3, 2 >; int[] result = IntStream.rangeClosed(1, initialArray.length) .map(i -> initialArray[initialArray.length - i]) .toArray(); int[] reversedArray = < 2, 3, 8, 5, 9, 1 >; assertArrayEquals(reversedArray, result); > 

As we can see, we used map to swap the elements. Then, we called the terminal operation toArray() to return the reversed array.

Using Guava API

Guava is a library provided by Google. It comes with a set of utility and helper classes.

For instance, it offers Lists.reverse() to return a reversed view of a given list.

Typically, the method accepts a list as a parameter. So, we need to call Arrays.asList() to pass an array:

 @Test public void reverseArrayUsingGuava() < Object[] initialArray = < "A", "B", "C", "D", "E", "F" >; Object[] result = Lists.reverse(Arrays.asList(initialArray)) .toArray(); Object[] reversedArray = < "F", "E", "D", "C", "B", "A" >; assertArrayEquals(reversedArray, result); > 

As shown above, since Lists.reverse() returns a list, we used the toArray() method to get the reversed elements as an array.

Using Apache Commons Library

Another solution would be using the Apache Commons Lang library.

It provides the ArrayUtils.reverse() method for inversing an array in a null-safe manner (it accepts null as a parameter).

 @Test public void reverseArrayUsingApacheCommonsLang() < String[] initialArray = < "A", "B", "C", "D", "E", "F" >; ArrayUtils.reverse(initialArray); String[] reversedArray = < "F", "E", "D", "C", "B", "A" >; assertArrayEquals(reversedArray, initialArray); > 

Please bear in mind that Guava and Apache Commons are external libraries, so we need to add their dependencies in pom.xml

Conclusion

To sum it up, we have covered in-depth everything you need to know about how to reverse an array in Java.

Along the way, we have seen how to use Java 7 and Java 8 methods to achieve this.

Then, we showcased how to use external libraries such as Guava and Apache Commons to accomplish the same objective.

Liked the Article? Share it on Social media!

If you enjoy reading my articles, buy me a coffee ☕. I would be very grateful if you could consider my request ✌️

Источник

Java Sort Array – How to Reverse an Array in Ascending or Descending Order with Arrays.sort()

Ihechikara Vincent Abba

Ihechikara Vincent Abba

Java Sort Array – How to Reverse an Array in Ascending or Descending Order with Arrays.sort()

In Java, you use arrays to store a collection of variables (with the same data type) in a single variable.

In many cases, the values stored in an array appear in a random order. Using the Arrays class in Java, you have access to various methods you can use to manipulate arrays.

One of the methods we’ll be using from the Arrays class is the sort() method which sorts an array in ascending order.

We’ll also see how to sort an array in descending order using the reverseOrder() method from the Collections class in Java.

How to Sort an Array in Ascending Order in Java Using Arrays.sort()

In this section, we’ll see an example on how we can use the sort() method to sort an array in ascending order.

import java.util.Arrays; class ArraySort < public static void main(String[] args) < int[] arr = < 5, 2, 1, 8, 10 >; Arrays.sort(arr); for (int values : arr) < System.out.print(values + ", "); // 1, 2, 5, 8, 10, >> >

The first thing we did in the example above was to import the Arrays class: import java.util.Arrays; . This give us access to all the methods of the Arrays class.

We then created an array with numbers in a random order: int[] arr = < 5, 2, 1, 8, 10 >; .

In order to sort this array in ascending order, we passed in the array as parameter to the sort() method: Arrays.sort(arr); .

Note that the Arrays class was written first before accessing the sort() method using dot notation.

Lastly, we looped through and printed the array in the console. The result was a sorted array: 1, 2, 5, 8, 10 .

In the next section, we’ll talk about sorting an array in descending order.

How to Sort an Array in Descending Order in Java Using Collections.reverseOrder()

To sort an array in descending order, we use the reverseOrder() which we can access from the Collections class.

We’ll still make use of Arrays.sort(); , but in this example, it’ll take in two parameters – the array to be sorted and Collections.reverseOrder() .

import java.util.Arrays; import java.util.Collections; class ArraySort < public static void main(String[] args) < Integer[] arr = < 5, 2, 1, 8, 10 >; Arrays.sort(arr, Collections.reverseOrder()); for (int values : arr) < System.out.print(values + ", "); // 10, 8, 5, 2, 1, >> >

First things first, we imported the Arrays and Collections classes because we’ll be making use the methods provided by the classes.

We then created an array of numbers in random order: Integer[] arr = < 5, 2, 1, 8, 10 >; . You’ll notice that we used Integer[] instead of int[] like we did in the last example – the latter would throw an error.

To sort the array in descending order, we did this: Arrays.sort(arr, Collections.reverseOrder()); .

The first parameter is the array arr which will be sorted in ascending order. The second parameter – Collections.reverseOrder() – will then reverse the order of the sorted array so it is arranged in descending order.

When looped through and printed, the array would look like this: 10, 8, 5, 2, 1 .

Summary

In this article, we talked about sorting arrays in Java. Arrays can be sorted in ascending or descending order.

We can sort arrays in ascending order using the sort() method which can be accessed from the Arrays class. The sort() method takes in the array to be sorted as a parameter.

To sort an array in descending order, we used the reverseOrder() method provided by the Collections class. This is passed in as a second parameter in the sort() method so that the sorted array can be rearranged in descending order.

Источник

Читайте также:  Пример простой страницы html
Оцените статью