2

I will send two variables and if the variables are to be checked whether it is null or not. If it is not null then concatenate two Strings with any Delimiter. Else return only one or Empty String.

Do we have any inbuilt method to test or any better way than below?

private String getValue(String valueOne, String valueTwo) {
    String value = null;
    if(valueOne != null) {
        value = valueOne;
    }
    if(value != null && valueTwo != null) {
        value += "-" + valueTwo;
    }else if(valueTwo != null) {
        value = valueTwo;
    }
    return value !=null ? value : "";
}
a = "abc" and b = "efg"
OUTPUT: "abc-efg"
a = null and b = "abc"
OUTPUT: "abc";

4 Answers4

9

I choose to accept any number arguments, but changing to accept only two is easy, you can then still use Stream.of

private String getValue2(String... values) {
    return Stream.of(values)
            .filter(Objects::nonNull)
            .collect(Collectors.joining("-"));
}
2

You could refactor to the following structure which also checks for empty strings and gradually returns on finding a suitable configuration.

private String getValue(String valueOne, String valueTwo) 
{
      if(isNullOrEmpty(valueOne) && isNullOrEmpty(valueTwo))
      {
         return "";
      }
      else if (isNullOrEmpty(valueOne))
      {
        return valueTwo;
      }
      else if (isNullOrEmpty(valueTwo))
      {
       return valueOne;
      }

    return valueOne.concat("-").concat(valueTwo);    
}

 private boolean isNullOrEmpty(String str)
 {
    return str == null || str.isEmpty();
 }
robingood
  • 319
  • 2
  • 10
0

You can use optional for this case. Also it is nice to replace String from paramerets to Optional, In this case the method could be simplified.

private String getValue(String valueOne, String valueTwo) {
        Optional<String> valOne = Optional.ofNullable(valueOne);
        Optional<String> valTwo = Optional.ofNullable(valueTwo);
        return valOne.orElse("") +
                ((valOne.isPresent() && valTwo.isPresent()) ? "-" : "") +
                valTwo.orElse("");
}
i.bondarenko
  • 3,442
  • 3
  • 11
  • 21
0

I would try to rewrite it with more readability like below:

private String getValue(@Nonnull String mandatoryStr, Optional<String> optionalStr) {

    if (optionalStr.isPresent()) {
        mandatoryStr += "-" + optionalStr;
    }
    return mandatoryStr;
}

Of course you would have to import these imports:

import javax.annotation.Nonnull;
import java.util.Optional;
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62