code: protected String collapse(String string) {
  
          int len = string.length();
          StringBuffer result = new StringBuffer(len);
          int state = 0;
          for (int i = 0; i < len; i++) {
              char c = string.charAt(i);
              switch (c) {
                  // see HTML specification section 9.1 White space
                  // http://www.w3.org/TR/html4/struct/text.html#h-9.1
                  case '\u0020':
                  case '\u0009':
                  case '\u000C':
                  case '\u200B':
                  case '\r':
                  case '\n':
                      if (0 != state) {
                          state = 1;
                      }
                      break;
                  default:
                      if (1 == state) {
                          result.append(' ');
                      }
                      state = 2;
                      result.append(c);
              }
          }
          return result.toString();
      }
docs: Collapse HTML whitespace in the given String.<p>
  
  @param string the string to collapse
  
  @return the input String with all HTML whitespace collapsed