Tuesday, May 1, 2018

Reverse a string array !!

Problem statement: Reverse a string array in java !
Using for Loop:
  1. public class ReverseStringArrayExe1 {
  2. public static void main(String[] args) {

  3. String a[] = { "apples", "tomatoes", "bananas", "guavas", "pineapples" };
  4. for (int i = 0; i < a.length / 2; i++) {
  5. Object temp = a[i];
  6. a[i] = a[a.length - 1 - i];
  7. a[a.length - 1 - i] = (String) temp;

  8. }
  9. for (String s : a) {
  10. System.out.print(s + " ");

  11. }
  12. }
  13. }
Output: 
pineapples guavas bananas tomatoes apples
Time complexity: O(n/2)

Using while Loop:
  1. public class ReverseStringArray {
  2. public static void main(String[] args) {
  3. String a[] = { "apples", "tomatoes", "bananas", "guavas", "pineapples" };
  4. int end = a.length - 1;
  5. int start = 0;
  6. String temp;
  7. while (start < end) {
  8. temp = a[start];
  9. a[start] = a[end];
  10. a[end] = temp;
  11. start++;
  12. end--;
  13. }
  14. for (String i : a) {
  15. System.out.print(i + " ");
  16. }
  17. }
  18. }
Output:
pineapples guavas bananas tomatoes apples
Time complexity: O(n/2)

Using Java 8 Stream API:
  1. import java.util.stream.IntStream;

  2. public class ReverseArrayUsingStream {
  3. public static void main(String[] args) {
  4. String a[] = { "apples", "tomatoes", "bananas", "guavas", "pineapples" };
  5. reverseUsingStream(a);
  6. }

  7. static void reverseUsingStream(Object a[]) {

  8. Object rev[] =IntStream.rangeClosed(1, a.length).mapToObj(i -> a[a.length - i]).toArray();
  9. for (Object s : rev) {
  10. System.out.print(s + " ");
  11. }
  12. }
  13. }
Output:
pineapples guavas bananas tomatoes apples 

Using Collections.reverse() :
  1. import java.util.List;
  2. import java.util.Arrays;
  3. import java.util.Collections;

  4. public class ReverseArrayCollections {
  5. public static void main(String[] args) {
  6. String a[] = { "apples", "tomatoes", "bananas", "guavas", "pineapples" };
  7. reverseUsingCollectionsUtils(a);
  8. }
  9. static void reverseUsingCollectionsUtils(Object[] array) {
  10. List<Object> list = Arrays.asList(array);
  11. Collections.reverse(list);
  12. for (Object i : list) {
  13. System.out.print(i + " ");
  14. }
  15. }
  16. }
Output:
pineapples guavas bananas tomatoes apples

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...