The challenge

Complete the solution so that it reverses all of the words within the string passed in.

Example:

1
2
ReverseWords.reverseWords("The greatest victory is that which requires no battle");
// should return "battle no requires which that is victory greatest The"

The solution in Java code

Option 1 (using StringBuilder):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class ReverseWords{

 public static String reverseWords(String str){
     String[] words = str.split(" ");
   
     StringBuilder sb = new StringBuilder();
     
     for (int i=words.length-1; i>=0; i--) {
         sb.append(words[i]).append(" ");
     }
     
     return sb.toString().trim();
 }

}

Option 2 (using Arrays):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import java.util.*;

public class ReverseWords{

 public static String reverseWords(String str){
     List Words = Arrays.asList(str.split(" "));
     Collections.reverse(Words);
     return String.join(" ", Words);
 }

}

Option 3 (using streams):

1
2
3
4
5
6
7
8
9
import java.util.Arrays;

public class ReverseWords{

 public static String reverseWords(String str){
     return Arrays.stream(str.split(" ")).reduce((x, y) -> y+" "+x).get();
 }

}

Test cases to validate our solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void testSomething() {
         assertEquals("eating like I", ReverseWords.reverseWords("I like eating"));
         assertEquals("flying like I", ReverseWords.reverseWords("I like flying"));
         assertEquals("nice is world The", ReverseWords.reverseWords("The world is nice"));
         assertEquals("nice so not is world The", ReverseWords.reverseWords("The world is not so nice"));
         assertEquals("beatiful is Life", ReverseWords.reverseWords("Life is beatiful"));
         assertEquals("won! we hello Hello", ReverseWords.reverseWords("Hello hello we won!"));
    }
}