Java 8 – How to Reverse a String in place ?

In this article, we will see how to reverse a String in place using traditional & Java 8 Stream approaches

1. Traditional approach :

  • Here, we will create a StringBuilder object with the given input String after trimming for any leading or trailing white-spaces
  • Iterate through the string length for reversing the string by swapping approach
  • Finally, test the reverse program with different set of input strings like
    • odd length string
    • even length string
    • leading white-spaces
    • trailing white-spaces
    • leading & trailing white-spaces
    • null
    • empty string
    • empty string with whitespaces

ReverseStringInPlace.java

package in.bench.resources.reverse.string;

public class ReverseStringInPlace {

	// main() method
	public static void main(String[] args) {

		// strings in different formats
		String[] strArrays = {
				"India", // odd length string
				"France", // even length string
				"   China", // leading white-spaces
				"Bhutan   ", // trailing white-spaces
				"   America   ", // leading & trailing white-spaces
				null, // null
				"", // empty string
				"  " // empty string with white-spaces
		};


		// invoke/test & print to console
		for(String str : strArrays) {

			System.out.println("Original String :- " + str);
			System.out.println("Reversed String :- " + reverseString(str) + "\n");
		}
	}


	/**
	 * method to reverse the string using traditional for-loop
	 * 
	 * @param input
	 * @return
	 */
	private static String reverseString(final String input) {

		if(null == input || input.isEmpty() || input.trim().length() == 0) {
			return "INVALID string";
		}

		// local variable
		StringBuilder sbd = new StringBuilder(input.trim());


		// get length of input String
		int length = input.trim().length();


		// iterate through each characters of input String
		for(int index = 0; index < length/2; index++) {


			// get in-place character for swapping
			final char leftChar = sbd.charAt(index);
			final int rightCharIndex = length - 1 - index;
			final char rightChar = sbd.charAt(rightCharIndex);


			// actual swapping
			sbd.setCharAt(index, rightChar);
			sbd.setCharAt(rightCharIndex, leftChar);
		}


		// return reversed string
		return sbd.toString();
	}
}

Output :

Original String :- India
Reversed String :- aidnI

Original String :- France
Reversed String :- ecnarF

Original String :-    China
Reversed String :- anihC

Original String :- Bhutan   
Reversed String :- natuhB

Original String :-    America   
Reversed String :- aciremA

Original String :- null
Reversed String :- INVALID string

Original String :- 
Reversed String :- INVALID string

Original String :-   
Reversed String :- INVALID string

2. Java 8 Stream approach :

  • Iterate through the string length using range() method of IntStream starting from index 0 till length minus one (where start-index is inclusive & end-index is exclusive)
  • Map the object in reverse order using Stream.mapToObj() method and collect it to new StringBuilder object using constructorreferences
  • Finally, test the reverse program with different set of input strings as shown in the above example

ReverseStringInPlaceUsingJava8Stream.java

package in.bench.resources.reverse.string;

import java.util.Arrays;
import java.util.stream.IntStream;

public class ReverseStringInPlaceUsingJava8Stream {

	// main() method
	public static void main(String[] args) {

		// strings in different formats
		String[] strArrays = {
				"India", // odd length string
				"France", // even length string
				"   China", // leading white-spaces
				"Bhutan   ", // trailing white-spaces
				"   America   ", // leading & trailing white-spaces
				null, // null
				"", // empty string
				"  " // empty string with white-spaces
		};


		// invoke/test & print to console
		Arrays.stream(strArrays).forEach(str -> {
			System.out.println("Original String :- " + str);
			System.out.println("Reversed String :- " + reverseString(str) + "\n");
		});
	}


	/**
	 * method to reverse the string using Java 8 Stream API
	 * 
	 * @param input
	 * @return
	 */
	private static String reverseString(final String input) {

		if(null == input || input.isEmpty() || input.trim().length() == 0) {
			return "INVALID string";
		}

		return IntStream
				.range(0, input.length())
				.mapToObj(index -> input.charAt(input.length() - 1 - index))
				.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
				.toString();
	}
}

Output :

Original String :- India
Reversed String :- aidnI

Original String :- France
Reversed String :- ecnarF

Original String :-    China
Reversed String :- anihC   

Original String :- Bhutan   
Reversed String :-    natuhB

Original String :-    America   
Reversed String :-    aciremA   

Original String :- null
Reversed String :- INVALID string

Original String :- 
Reversed String :- INVALID string

Original String :-   
Reversed String :- INVALID string

Related Articles :

References:

Happy Coding !!
Happy Learning !!

Java 8 - Optional class in detail
Java 8 - How to find common & uncommon elements from 2 Lists ?