Skip to content
Advertisement

How to simplify String concat in java?

Given the following code:

private static final String DELIMITER = " ";

  @AfterMapping
  protected void createCompactInfo(@MappingTarget User user) {
    String vorname = Optional.ofNullable(user.getVorname()).orElse(Strings.EMPTY);
    String nachname = Optional.ofNullable(user.getNachname()).orElse(Strings.EMPTY);
    String email = Optional.ofNullable(user.getEmail()).orElse(Strings.EMPTY);
    String compactInfo =
        (vorname
                + DELIMITER
                + nachname
                + DELIMITER
                + (email.isEmpty() ? Strings.EMPTY : "(" + email + ")"))
            .trim();
    if (compactInfo.isEmpty()) {
      user.setCompakt(
          Optional.ofNullable(user.getId()).orElse(Strings.EMPTY));
    } else {
      user.setCompakt(compactInfo);
    }

I am trying and discussing in the team how the simpliest code could look like while one could use also constructs like:

  • org.apache.commons.lang3.StringUtils: defaultString()
  • MoreObjects.firstNonNull(user.getVorname(), Strings.EMPTY)

A possible test could be like (expected results are visible here too):

private static Stream<Arguments> arguments() {
    return Stream.of(
        Arguments.of("Peter", "Silie", "peter@silie.org", "BOND", "Peter Silie (peter@silie.org)"),
        Arguments.of(null, "Silie", "peter@silie.org", "BOND", "Silie (peter@silie.org)"),
        Arguments.of("Peter", null, "peter@silie.org", "BOND", "Peter (peter@silie.org)"),
        Arguments.of("Peter", "Silie", null, "BOND", "Peter Silie"),
        Arguments.of(null, "Silie", null, "BOND", "Silie"),
        Arguments.of(null, null, "peter@silie.org", "BOND", "(peter@silie.org)"),
        Arguments.of("Peter", null, null, "BOND", "Peter"),
        Arguments.of(null, null, null, "BOND", "BOND"));
  }

  @ParameterizedTest(
      name = "{index}" + ". Test: vorname={0}, nachname={1}, email={2}; expected: {3}")
  @MethodSource(value = "arguments")
  void verifyUserKompakt(
      String vorname, String nachname, String email, String kuerzel, String expectedResult) {

    // arrange
    Base base =
        Base.builder()
            .vorname(vorname)
            .nachname(nachname)
            .email(email)
            .kuerzel(kuerzel)
            .build();

    // act
    User userResult =
        userMapperImpl.doIt(base);

    // assert
    assertThat(userResult.getUserKompakt()).isEqualTo(expectedResult);
  }

Any ideas welcome… what could I try?

BTW: java 17 is allowed 🙂

The following code seemss to be very close but does not handle the braces for email if existing:

String compactInfo =
        (Stream.of(
                    user.getVorname(),
                    user.getNachname(),
                    user.getEmail())
                .map(s -> s != null ? s : "")
                .collect(Collectors.joining(" ")))
            .trim();

    user.setUserKompakt(
        compactInfo.isEmpty()
            ? Optional.ofNullable(user.getKuerzel()).orElse("")
            : compactInfo);

Advertisement

Answer

Since you have duplicated code to transform vorname, nachname and userId you may want to extract the logic to a Function or an UnaryOperator because it is a string to string transformation and an additional one for the email. Example

import java.util.function.UnaryOperator;

....

private static final String EMPTY = "";
private static final String DELIMITER = " ";

UnaryOperator<String> nameOp = o -> Optional.ofNullable(o).orElse(EMPTY);
UnaryOperator<String> mailOp = o -> Optional.ofNullable(o).map(s -> String.format("(%s)", s)).orElse(EMPTY);

@AfterMapping
protected void createCompactInfo(@MappingTarget User user) {
   String compactInfo = Stream.of(nameOp.apply(user.getVorname()),
                                  nameOp.apply(user.getNachname()),
                                  mailOp.apply(user.getEmail()))
                               .filter(Predicate.not(String::isEmpty))
                               .collect(Collectors.joining(DELIMITER));

   user.setCompakt(compactInfo.isEmpty() ? nameOp.apply(user.getId()) : compactInfo);
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement