Reverse a string array in java

Hey guys!! Welcome to flower brackets blog. Today we are going to learn reverse a string array in java.

reverse a string array in java

To reverse string array, 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.

Also read Рbest way to reverse a string in java

Here’s the java program,

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

public class ReverseStringArray
{
   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:

Reversed string array :
CEO
Senior Manager
Project Manager
Team Lead
Senior Developer
Junior Developer


Now let’s learn another way to reverse string array,

import java.util.Arrays;

public class ArrayUtilsReverse 
{
   public static void main(String[] args) 
   {
      String strArray[] = { "weekend.", "the", "enjoy", "let's", "Come" };
      System.out.println("String array in reverse order : " + 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:

String array in reverse order java : [weekend., the, enjoy, let’s, Come]
Reversed array :
Come
let’s
enjoy
the
weekend.

Related Posts