Java: Remove duplicate whitespace in strings

str = str.replaceAll("\\s+", " ");


Input Result
"lorem    ipsum" "lorem ipsum"
"lorem\nipsum" "lorem\nipsum"
"lorem  ipsum   dolor \n sit." "lorem ipsum dolor sit"

What does that \s+ mean?

\s+ is a regular expression. \s matches a space, tab, new line, carriage return, form feed or vertical tab, and + says “one or more of those”. In other words the above code will replace all whitespace substrings with a single space character.