Check Null and Combine Two String with Delimiter in Java else Return One[Java -7]

sathish kumar :

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";
Martin van Wingerden :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=310612&siteId=1