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:
It is demonstrated in the following program:
File name: ReverseStringUsingCollections.java
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
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.