Java 8 – Reverse each words in a String using Stream and Collectors

In this article, we will learn how to reverse each words in a String using different approaches

Reverse each words in a String :

  • Reverse using Java 8 Stream & Collectors
  • Reverse using StringBuilder & for-loop
  • Reverse using Iterative approach

1. Reverse using Java 8’s Stream & Collectors

ReverseEachWordsInStringUsingJava8.java

package in.bench.resources.count.lines.words;

import java.util.Arrays;
import java.util.stream.Collectors;

public class ReverseEachWordsInStringUsingJava8 {

	public static void main(String[] args) {

		// sample string
		String str = "quick brown fox jumps over lazy dog";


		// reverse a String using Java 8
		String reverseStr = Arrays
				.stream(str.split(" "))
				.map(word -> new StringBuilder(word).reverse())
				.collect(Collectors.joining(" "));


		// print both strings to console
		System.out.println("Original String = " + str);
		System.out.println("Reversed String = " + reverseStr);


		// print both string length to console
		System.out.println("\n\nOriginal String length = " + str.length());
		System.out.println("Reversed String length = " + reverseStr.length());

	}
}

Output:

Original String = quick brown fox jumps over lazy dog
Reversed String = kciuq nworb xof spmuj revo yzal god


Original String length = 35
Reversed String length = 35

2. Reverse using StringBuilder & for-loop

  • First declare 2 StringBuilder objects
    • Main sbd object will hold partial result in each iteration and eventually complete result at the end of the iteration
    • another temporary sbd object is used to reverse words and append space delimiter
  • Split original input String with space as delimiter using String.split() method
  • Iterate through String[] array,
    • create temporary sbd object and append word and reverse it
    • Append reversed word to the Main sbd object for storing partial result
  • At the end of the for-loop iteration, Main sbd object will have final reversed words in a String
  • We will print both original/reversed Strings along with this length

ReverseEachWordsInString.java

package in.bench.resources.count.lines.words;

public class ReverseEachWordsInString {

	public static void main(String[] args) {

		// local variables
		StringBuilder sbfTemp = null;
		StringBuilder resultReverseStr = new StringBuilder();


		// sample string
		String inputStr = "quick brown fox jumps over lazy dog";


		// split String on the basis of space
		String[] strArray = inputStr.split("\\s");


		// iterate through String[] array after splitting
		for(String str : strArray) {

			// create StringBuilder object
			sbfTemp = new StringBuilder();


			// append String and reverse 
			String tempStr = sbfTemp.append(str).reverse().toString();


			// append space and reversed String
			resultReverseStr.append(" ").append(tempStr);
		}


		// reversed String
		String reversedStr = resultReverseStr.toString();


		// print both strings to console
		System.out.println("Original String = " + inputStr.trim());
		System.out.println("Reversed String = " + reversedStr.trim());


		// print both string length to console
		System.out.println("\n\nOriginal String length = " + inputStr.trim().length());
		System.out.println("Reversed String length = " + reversedStr.trim().length());		
	}
}

Output:

Original String = quick brown fox jumps over lazy dog
Reversed String = kciuq nworb xof spmuj revo yzal god


Original String length = 35
Reversed String length = 35

3. Reverse using Iterative approach

  • Initially, we got a String “quick brown fox jumps over lazy dog
  • Let’s split String based on the space delimiter which will return String[] array
  • Iterate through String[] array by passing each words to a method
  • Inside method,
    • Iterate through each characters in a word one-by-one in reverse-way using String.charAt(index) method
    • At the same time, concatenate using + (plus) operator and store it in local variable and return the same
  • Now, in the main() method, concatenate returned reversed words along with a space character at the end
  • We will print both original/reversed Strings along with this length

ReverseEachWordsInStringUsingIterativeApproach.java

package in.bench.resources.count.lines.words;

public class ReverseEachWordsInStringUsingIterativeApproach {

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

		// local variable
		String reverseStr = "";


		// sample string
		String str = "quick brown fox jumps over lazy dog";


		// split String based on space delimiter
		String[] words = str.split(" ");


		// iterate through each words
		for(String word : words) {

			// invoke reverse String method and concatenate String & single space
			reverseStr = reverseStr + reverseString(word) + " ";
		}


		// print both strings to console
		System.out.println("Original String = " + str);
		System.out.println("Reversed String = " + reverseStr.trim());


		// print both string length to console
		System.out.println("\n\nOriginal String length = " + str.length());
		System.out.println("Reversed String length = " + reverseStr.trim().length());
	}


	/**
	 * This method is used to reverse String using Iterative approach
	 * 
	 * @param word
	 * @return
	 */
	private static String reverseString(String word) {

		// local variable
		String reverseWord = "";


		// reverse word by iterating in reverse-way		
		for(int index = (word.length() - 1); index >= 0; index--) {

			// concatenate each iterating characters using + (plus) operator
			reverseWord = reverseWord + word.charAt(index);
		}

		// return
		return reverseWord;
	}
}

Output:

Original String = quick brown fox jumps over lazy dog
Reversed String = kciuq nworb xof spmuj revo yzal god


Original String length = 35
Reversed String length = 35

References:

Happy Coding !!
Happy Learning !!

Java 8 – Reverse complete String using Stream and Collectors
Java 8 – Count and print number of repeated character occurrences in a String