code: public static String normalizeWS(String value) {
      char[] tmp = new char[value.length()];
      int pos = 0;
      boolean prevws = false;
      for (int ix = 0; ix < tmp.length; ix++) {
        char ch = value.charAt(ix);
        if (ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r') {
          if (prevws && pos != 0)
            tmp[pos++] = ' ';
  
          tmp[pos++] = ch;
          prevws = false;
        } else
          prevws = true;
      }
      return new String(tmp, 0, pos);
    }
docs: Removes trailing and leading whitespace, and also reduces each
  sequence of internal whitespace to a single space.