code: public String trimAndCollapseFrom(CharSequence sequence, char replacement) {
      // This implementation avoids unnecessary allocation.
      int len = sequence.length();
      int first;
      int last;
  
      for (first = 0; first < len && matches(sequence.charAt(first)); first++) {}
      for (last = len - 1; last > first && matches(sequence.charAt(last)); last--) {}
  
      return (first == 0 && last == len - 1)
          ? collapseFrom(sequence, replacement)
          : finishCollapseFrom(
                sequence, first, last + 1, replacement,
                new StringBuilder(last + 1 - first),
                false);
    }
docs: Collapses groups of matching characters exactly as {@link #collapseFrom} does, except that
  groups of matching characters at the start or end of the sequence are removed without
  replacement.
  
  @param sequence the sequence
  @param replacement the replacement
  @return the string