Необязательная / условная конкатенация строк - PullRequest
1 голос
/ 30 апреля 2020

Я пытаюсь объединить String условно. Например, в методе у меня есть два параметра и локальная переменная String. Если я предоставлю значения для этих параметров, то эти значения будут добавлены в локальную переменную String.

public Object concatinateString(String a, String b){

   String xyz = "firstValue";

   if((a == null || a == "") && (b != null || b != "")) {

        xyz = xyz.concat(".").concat(b);
   }

   if((b == null || b == "") && (a != null || a != "")) {

        xyz = xyz.concat(".").concat(a);
   }

   xyz = xyz.concat(".").concat(a).concat(".").concat(b);
} 

что я ожидаю:

  concatinateString(null, b) --> xyz = firstValue.b;

  concatinateString("", b) --> xyz = firstValue.b

  concatinateString(a, null) --> xyz = firstValue.a

  concatinateString(a, "") --> xyz = firstValue.a

  concatinateString("", "") --> xyz = firstValue

  concatinateString(null, null) --> xyz = firstValue

  concatinateString(a, b) --> xyz = firstValue.a.b

I также пробовал следующий код, но не получил ожидаемый результат.

public Object concatinateString(Optional<String> stageName, Optional<String> systemName) {
        Optional<String> property = Optional.of("firstValue");

        if ((!stageName.isPresent() || stageName.equals("")) && systemName.isPresent()) {

            property = Stream.of(property, systemName).flatMap(x -> x.map(Stream::of).orElse(null)).reduce((a, b) -> a + "." + b);

        }
        if (((!systemName.isPresent() || systemName.equals(""))) && stageName.isPresent()) {
            property = Stream.of(property, stageName).flatMap(x -> x.map(Stream::of).orElse(null)).reduce((a, b) -> a + "." + b);
        }
        property = Stream.of(property, stageName, systemName)
                .flatMap(x -> x.map(Stream::of).orElse(null))
                .reduce((a, b) -> a + "." + b);

        return property;

    }


 public static void main(String[] args) {
        Person person = new Person();
        System.out.println(person.concatinateString(Optional.ofNullable(null),Optional.ofNullable(null)));
}

Результат, который я получаю:

  concatinateString(null, b) --> xyz = firstValue.b.b

  concatinateString("", b) --> xyz = firstValue..b

  concatinateString(a, null) --> xyz = firstValue.a.a

  concatinateString(a, "") --> xyz = firstValue.a.

  concatinateString("", "") --> xyz = firstValue..

  concatinateString(null, null) --> xyz = firstValue

  concatinateString(a, b) --> xyz = firstValue.a.b 

Ответы [ 2 ]

0 голосов
/ 01 мая 2020

Если вам нужно больше объяснений, давайте расшифруем ваше первое условие:

if((a == null || a == "") && (b != null || b != "")) {

        xyz = xyz.concat(".").concat(b);
   }

Здесь важна эта часть: (b! = Null || b! = ""). Действительно, давайте посмотрим случай, когда b == ноль.

If b == null, (b != null) returns 0, and (b != "") returns 1.

In this case, (0 || 1) returns 1. But, it should return 0.

Теперь, если b == "".

If b == "", (b != null) returns 1, and (b != "") returns 0.

Here, (1 || 0) returns 1. But again, it should return 0.

Теперь, если вы поставите && вместо || in (b! = null || b! = ""),

If b == null, (b != null) returns 0, and (b != "") returns 1.

(1 && 0) returns 0.

If b == "", (b != null) returns 1, and (b != "") returns 0.

(0 && 1) returns 0.

Тогда, только если b отличается от "" и null, вы получите: (1 && 1), который возвращает 1 и объединяет b в xyz.

Надеюсь, это поможет.

0 голосов
/ 30 апреля 2020

если я правильно понимаю ваш вопрос, ваша проблема была в условиях. Действительно, если вы хотите получить firstvalue + b, a должно быть равно "" или null, но b должно отличаться от "" AND null. Но ваше состояние говорит b! = "" || b! = ноль. Вот как я вижу это:

if ((a != "" && a != null) && (b == "" || b == null)){

    firstvalue + a;

} else if ((b != "" && b != null) && (a == "" || a == null)) {

    firstvalue + b;

} else if ((a != "" && a != null) && (b != "" && b != null)) {

    firstvalue + a + b;

} else if ((a == "" || a == null) && (b == "" || b == null)) {

    firstvalue;

}

Он должен вернуть то, что вы ожидали:

concatinateString (a, null) -> xyz = firstValue.a

concatinateString (a, "") -> xyz = firstValue.a

concatinateString (null, b) -> xyz = firstValue.b;

concatinateString ("", b) - > xyz = firstValue.b

concatinateString (a, b) -> xyz = firstValue.ab

concatinateString ("", "") -> xyz = firstValue

concatinateString (null, null) -> xyz = firstValue

Добавление этого тоже:

concatinateString (null, "") -> xyz = firstValue

concatinateString ("", null) -> xyz = firstValue

Я надеюсь, что это решение подойдет. Пока!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...