This post will discuss how to remove duplicate whitespaces from a String in Java.

1. Using String.replaceAll() method

To remove duplicate whitespaces from a string, you can use the regular expression \s+ which matches with one or more whitespace characters, and replace it with a single space ' '. This can be done using the replaceAll() method, which replaces each substring of the string that matches the given regex with the specified replacement.

Download  Run Code

Output:

Hello World

 
The above solution does not remove the leading and trailing spaces from the string. You can call the trim() method to eliminate spaces at the beginning and end of the string. It can be called before (or after) making a call to the replaceAll() method.

Download  Run Code

Output:

Hello World

 
The regex \s+ matches with one or more whitespace characters. To match with exactly two or more whitespace characters, a better alternative is to use the regex \s{2,}.

Download  Run Code

Output:

Hello World

 
You might want to compile the regular expression for performance boost (when regex is called multiple times):

Download  Run Code

Output:

Hello World

2. Using Apache Commons Lang

If you prefer Apache Commons Lang library, you can use the StringUtils.normalizeSpace() method for this specific task. It removes the leading and trailing whitespace from the specified string, and then replaces sequences of whitespace characters by a single space.

Download Code

Output:

Hello World

That’s all about removing duplicate whitespaces from a String in Java.