Reverse Words in String without Changing Order

Learn to reverse the words in a Java String such that each word remains in its order, only the characters in the words are reversed in place using Java 8 Stream API and StringUtils classes.

Original String – “alex brian charles”

Reversed words – “xela nairb selrahc”

1. Using Stream and StringBuilder

The algorithm to reverse each word is simple:

  • Tokenize the string using String.split() method.
  • Loop through string array using Stream and use StringBuilder.reverse() method to reverse each word.
  • Join all reversed words by joining the Stream elements.
String input = "alex brian charles";

String reversed = Arrays.stream(input.split(" "))
    .map(word -> new StringBuilder(word).reverse())
    .collect(Collectors.joining(" "));

System.out.println(reversed);

Program output.

xela nairb selrahc

2. Using StringUtils

The StringUtils class is from the Apache command lang3 library. Its reverseDelimited() API reverses each word and joins the string back with the same delimiter. In our case, we will use a space character as delimiter.

String input = "alex brian charles";

String reversed = StringUtils.reverseDelimited(StringUtils.reverse(input), ' ');

System.out.println(reversed);

Program output.

xela nairb selrahc

In this post, we learned to reverse each word in a sentence in Java.

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
5 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode