Javatpoint Logo
Javatpoint Logo

Reverse a String Using Java Collections

In this article, we'll go through how to use the Java Collections Framework's reverse() function to reverse a string.

The use of Collections.reverse() to reverse a string in Java is demonstrated in the example below. The full process is as follows:

  1. Using the String.toCharArray function, create an empty list of characters as well as fill it with the characters from the specified string ().
  2. Use the reverse() function of java.util.Collections to reverse the list.
  3. Use StringBuilder to transform the ArrayList into a String and then return the resultant string.

It is demonstrated in the following program:

File name: ReverseStringUsingCollections.java

Output:

The string after reversing is:   tniopTavaJ ot emocleW

In the solution above, ArrayList is first transformed into a StringBuilder, and then a string is created from a StringBuilder. Square brackets, commas, as well as a single space, can be taken out of an array list to turn it directly into a string. To do such, the code below uses String.replaceAll(). But this strategy is very ineffective and is to be avoided whenever possible.

File name: ReverseStringUsingCollections1.java

Output:

The string after reversing is tniopTavaJ ot emocleW

That was all there was to the reverse() method of the Java Collections Framework for a String.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA