How to Reverse Array Elements in Java

In this article, we will learn how to reverse elements of any array in Java. One of the easiest way to reverse array elements is using Collections.

Using collections this can be done in three steps:

1.First you have to convert array to appropriate list using Arrays.asList() method. Read How to convert array to list in Java

2.Next you can use Collections.reverse() method to reverse the list elements.

3.Now you can convert the list back to array using toArray() method defined in List interface. Read How to convert List to Array in Java

Let us understand how to reverse array elements in Java with below example.

Reverse Array Elements in Java

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

public class StringReverseExample {
	public static void main(String str[]){
		String[] technology = {"Java",".Net","Hadoop","AJAX"};
		
		//Convert to List
		List listOfTechnology = (List) Arrays.asList(technology);
		//reverse list
		Collections.reverse(listOfTechnology);
		//Convert to Array
		technology = (String[])listOfTechnology.toArray();
		
		//Print the Array
		for(String tech : technology){
			System.out.println(tech);
		}
	}
}
AJAX
Hadoop
.Net
Java

In the above article, you learned how to reverse array elements in Java.

Article tagged as
Author
Author: Amit Gupta
Published On: 27/11/2015
Last revised On: 28/11/2015
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media