Home > Back-end >  How to simplify String concat in java?
How to simplify String concat in java?

Time:10-28

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", "[email protected]", "BOND", "Peter Silie ([email protected])"),
        Arguments.of(null, "Silie", "[email protected]", "BOND", "Silie ([email protected])"),
        Arguments.of("Peter", null, "[email protected]", "BOND", "Peter ([email protected])"),
        Arguments.of("Peter", "Silie", null, "BOND", "Peter Silie"),
        Arguments.of(null, "Silie", null, "BOND", "Silie"),
        Arguments.of(null, null, "[email protected]", "BOND", "([email protected])"),
        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);

CodePudding user response:

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);
}

CodePudding user response:

There is a huge performance difference between Java ordinary concatenation and StringBuilder/StringBuffer.

Observing your method createCompactInfo when you are doing String concatenation: compactInfo = ... will result in bad performance.

I would suggest you to try StringBuilder or StringBuffer.

A String is an immutable object which means the value cannot be changed, so each time you do a concatenation strA strB will result in a new Object.

Compare the performance results between ordinary concatenation with StringBuilder:

public class ConcatenateString {
    public static void main (String[] args){
          String strFinal = "";
          long tStart = System.currentTimeMillis();
          for(int i = 0; i < 100000; i   ){
                 strFinal  = "a";
          }
          long tEnd = System.currentTimeMillis();
          long tResult = tEnd - tStart;
          System.out.println("Runtime with operator   = " tResult " ms");

     
          StringBuilder strBuilder = new StringBuilder();
          tStart = System.currentTimeMillis();
          for(int i = 0; i < 100000; i   ){
                 strBuilder.append("a");
          }
          tEnd = System.currentTimeMillis();
          tResult = tEnd - tStart;
          System.out.println("Runtime with StringBuilder= " tResult " ms");
    }
}

result (at: Darwin Macs-iMac Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021; RELEASE_X86_64 x86_64 - Intel I5 processor 2.5ghz):

Runtime with operator   = 1469 ms
Runtime with StringBuilder= 2 ms
  • Related