Java reverse string array

Let’s learn java reverse string array.

Java reverse string array

To reverse string array in java, Collections.reverse() method is used. This method reverses the order of the elements in the specified list. Its syntax,

public static void reverse(List<?> list)

list – the list whose elements are to be reversed.

Here’s the java program,

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

public class ReverseStringArrayInJava
{
   public static void main(String[] args)
   {
      String strHierarchy[] = new String[]{"Junior Developer","Senior Developer","Team Lead","Project Manager","Senior Manager","CEO"};
      List< String> li = Arrays.asList(strHierarchy);
      // Here we use reverse method of Collections class
      Collections.reverse(li);
      strHierarchy = (String[])li.toArray();
      System.out.println("Reversed string array : ");
      for(int x = 0; x < strHierarchy.length; x++)
      {
         System.out.println(strHierarchy[x]);
      }
   }
}



Output:

java reverse string array

Now let’s learn another way in java reverse string array example,

import java.util.Arrays;

public class ArrayUtilsReverse 
{
   public static void main(String[] args) 
   {
      String strArray[] = { "weekend.", "the", "enjoy", "let's", "Come" };
      System.out.println("Before : " + Arrays.toString(strArray));
      for(int a = 0; a < strArray.length / 2; a++)
      {
         String str = strArray[a];
         strArray[a] = strArray[strArray.length - a - 1];
         strArray[strArray.length - a - 1] = str; 
      }
      System.out.println("Reversed array : ");
      for(int a = 0; a < strArray.length; a++)
      {
         System.out.println(strArray[a]);
      }
   }
}



Output:

Before : [weekend., the, enjoy, let’s, Come]
Reversed array :
Come
let’s
enjoy
the
weekend.


Also read – how to rename file in java