Posted By

nulldev on 02/18/15


Tagged

java array String reverse


Versions (?)

Reverse String Array


 / Published in: Java
 

URL: http://www.java-examples.com/java-reverse-string-array-example

Reverses a Java string array, taken from: http://www.java-examples.com/java-reverse-string-array-example

  1. /*
  2.   Java Reverse String Array Example
  3.   This Java Reverse String Array example shows how to find sort an array of
  4.   String in Java using Arrays and Collections classes.
  5.  */
  6.  
  7. import java.util.Collections;
  8. import java.util.List;
  9. import java.util.Arrays;
  10.  
  11. public class ReverseStringArrayExample {
  12.  
  13. public static void main(String args[]){
  14.  
  15. //String array
  16. String[] strDays = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday"};
  17.  
  18. /*
  19.   * There are basically two methods, one is to use temporary array and
  20.   * manually loop through the elements of an Array and swap them or to use
  21.   * Arrays and Collections classes.
  22.   *
  23.   * This example uses the second approach i.e. without temp variable.
  24.   *
  25.   */
  26.  
  27. //first create a list from String array
  28. List<String> list = Arrays.asList(strDays);
  29.  
  30. //next, reverse the list using Collections.reverse method
  31. Collections.reverse(list);
  32.  
  33. //next, convert the list back to String array
  34. strDays = (String[]) list.toArray();
  35.  
  36. System.out.println("String array reversed");
  37.  
  38. //print the reversed String array
  39. for(int i=0; i < strDays.length; i++){
  40. System.out.println(strDays[i]);
  41. }
  42.  
  43. }
  44.  
  45. }
  46.  
  47. /*
  48. Output of above given Java Reverse String Array example would be
  49. String array reversed
  50. Wednesday
  51. Tuesday
  52. Monday
  53. Sunday
  54. */

Report this snippet  

You need to login to post a comment.