Problem statement: Reverse a string array in java !
Using for Loop:
pineapples guavas bananas tomatoes apples
Time complexity: O(n/2)
Using while Loop:
Using for Loop:
- public class ReverseStringArrayExe1 {
- public static void main(String[] args) {
- String a[] = { "apples", "tomatoes", "bananas", "guavas", "pineapples" };
- for (int i = 0; i < a.length / 2; i++) {
- Object temp = a[i];
- a[i] = a[a.length - 1 - i];
- a[a.length - 1 - i] = (String) temp;
- }
- for (String s : a) {
- System.out.print(s + " ");
- }
- }
- }
pineapples guavas bananas tomatoes apples
Time complexity: O(n/2)
Using while Loop:
- public class ReverseStringArray {
- public static void main(String[] args) {
- String a[] = { "apples", "tomatoes", "bananas", "guavas", "pineapples" };
- int end = a.length - 1;
- int start = 0;
- String temp;
- while (start < end) {
- temp = a[start];
- a[start] = a[end];
- a[end] = temp;
- start++;
- end--;
- }
- for (String i : a) {
- System.out.print(i + " ");
- }
- }
- }
Output:
pineapples guavas bananas tomatoes apples
Time complexity: O(n/2)
Using Java 8 Stream API:
Using Collections.reverse() :
Using Java 8 Stream API:
- import java.util.stream.IntStream;
- public class ReverseArrayUsingStream {
- public static void main(String[] args) {
- String a[] = { "apples", "tomatoes", "bananas", "guavas", "pineapples" };
- reverseUsingStream(a);
- }
- static void reverseUsingStream(Object a[]) {
- Object rev[] =IntStream.rangeClosed(1, a.length).mapToObj(i -> a[a.length - i]).toArray();
- for (Object s : rev) {
- System.out.print(s + " ");
- }
- }
- }
Output:
pineapples guavas bananas tomatoes apples
Using Collections.reverse() :
- import java.util.List;
- import java.util.Arrays;
- import java.util.Collections;
- public class ReverseArrayCollections {
- public static void main(String[] args) {
- String a[] = { "apples", "tomatoes", "bananas", "guavas", "pineapples" };
- reverseUsingCollectionsUtils(a);
- }
- static void reverseUsingCollectionsUtils(Object[] array) {
- List<Object> list = Arrays.asList(array);
- Collections.reverse(list);
- for (Object i : list) {
- System.out.print(i + " ");
- }
- }
- }
Output:
pineapples guavas bananas tomatoes apples
No comments:
Post a Comment