Search code examples
javastringbuilder

How can I add another string to stringbuilder?


I have this part of code which I don't understand correctly. I know that it builds a string out of values from the database. I think it's only the title:

private String createSearchFieldContent(Report report) {
  return createSearchFieldContent(report.getTitle(), report.getDescription());
}

private String createSearchFieldContent(OverrideableStringValue title,
                                        OverrideableStringValue description) {

  StringBuilder builder = new StringBuilder(getValue(title));
  if (StringUtils.isNotBlank(getValue(description))) {
    builder.append(" ").append(getValue(description));
  }
  String searchTerm = StringUtils.replaceAll(builder.toString(), "\n", " ");
  return unaccent(searchTerm);
}

I have another value which I'd like to add to the searchTerm. It's stored in report.getOwner(). How is it possible that I can build a new searchTerm which includes the title, description and owner?

Thanks!


Solution

  • Try below code :

    private String createSearchFieldContent(Report report) {
      return createSearchFieldContent(report.getTitle(), report.getDescription(), report.getOwner());
    }
    
    private String createSearchFieldContent(OverrideableStringValue title,
                                            OverrideableStringValue description, OverrideableStringValue owner) {
    
      StringBuilder builder = new StringBuilder(getValue(title));
      if (StringUtils.isNotBlank(getValue(description))) {
        builder.append(" ").append(getValue(description));
      }
      if (StringUtils.isNotBlank(getValue(owner))) {
        builder.append(" ").append(getValue(owner));
      }
      String searchTerm = StringUtils.replaceAll(builder.toString(), "\n", " ");
      return unaccent(searchTerm);
    }
    

    In the above code, we are passing the owner attribute to the createSearchFieldContent method like the other two, then the owner attribute is appended to string builder object just like description.