Reverse a string without reversing individual words in java

There are following way to Reverse a string without reversing individual words in java.

  • The word.split() method divides the string at the specified regex and returns an array of substrings.
  • Here Collections.reverse() method is reverse the order of the elements in the specified list.
  • Print the String array in reverse order
import java.util.Arrays;
import java.util.Collections;

public class ReverseSentence {
	public static void main(String[] args) {
		String str = "Hello World from Spring";
		String reversedSentence = reverseWords(str);
		System.out.println("reversed the word :- " + reversedSentence);

	}
	private static String reverseWords(String word) {
		String[] stArray = word.split(" ");
		Collections.reverse(Arrays.asList(stArray));
		return Arrays.toString(stArray);
	}
}

Output :-
reversed the word :- [Spring, from, World, Hello]