How to remove all duplicate whitespace in a string?

Question:
How can I remove duplicate whitespaces from a string.

Answer:
Use a while() loop indexing any double spaces and replacing them with single spaces.

Code:
public class RemoveDuplicates { 
 
   public static void main(String[] args) { 
 
      String str = "This   is a string   with    a  lot  of white   space."; 
      System.out.println("Before: " + str);
 
      while(str.indexOf("  ") >= 0){  
         str = str.replaceAll("  ", " ");  
      }
 
      System.out.println("After : " + str);
   } 
}

Output:
$ java RemoveDuplicates
Before: This   is a string   with    a  lot  of white   space.
After : This is a string with a lot of white space.