Concatenating Null Strings in Java – 在Java中串联空字符串

最后修改: 2021年 11月 30日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Java provides a variety of methods and classes for concatenating StringsHowever, the resultant String may contain some undesirable values if we don’t pay attention to null objects.

Java提供了各种方法和类来连接Strings然而,如果我们不注意null对象,产生的String可能包含一些不受欢迎的值。

In this tutorial, we will see some approaches to avoid null String objects while concatenating Strings.

在本教程中,我们将看到在连接Strings时避免null对象的一些方法。

2. Problem Statement

2 问题陈述

Let’s say we want to concatenate the elements of a String array where any of the elements may be null.

假设我们想连接一个String数组的元素,其中任何元素都可能是null

We can simply do this using the + operator:

我们可以简单地使用+运算符来做这件事。

String[] values = { "Java ", null, "", "is ", "great!" };
String result = "";

for (String value : values) {
    result = result + value;
}

This will concatenate all the elements into the resultant String, as seen below:

这将把所有元素串联成结果String,如下图所示。

Java nullis great!

But, we may not want to display or append such “null” values to the output.

但是,我们可能不想在输出中显示或附加这种 “空 “值。

Similarly, we get the same output using the String.join() static method, if our application is running on Java 8 or higher version:

同样,如果我们的应用程序运行在Java 8或更高版本上,我们使用String.join()静态方法得到同样的输出。

String result = String.join("", values);

We cannot avoid null elements from being concatenated while using the String.join() method either.

在使用String.join()方法时,我们也无法避免空元素被串联起来。

Let’s see some approaches to avoid those null elements from being concatenated and get the result we would expect: “Java is great!”.

让我们看看有哪些方法可以避免那些null元素被串联起来,并得到我们所期望的结果。”Java是伟大的!”。

3. Using the + Operator

3.使用 “+”运算符

The addition (+) operator is overloaded to concatenate Strings in Java. While concatenating using the + operator, we can check if the String is null, and replace the null String with an empty (“”) String:

在Java中,加法(+)运算符被重载用来连接Strings。当使用+运算符连接时,我们可以检查String是否为null,并用一个空的(“”)String替换null:。

for (String value : values) {
    result = result + (value == null ? "" : value);
}

assertEquals("Java is great!", result);

Alternatively, we can extract the code that checks for a null String into a helper method that accepts a String object and returns a non-null String object:

另外,我们可以将检查null String的代码提取到一个辅助方法中,该方法接受一个String对象并返回一个非null String对象。

for (String value : values) {
    result = result + getNonNullString(value);
}

Here, getNonNullString() method is our helper method. It simply checks for the null reference of the input String object. If the input object is null, it returns an empty (“”) String, otherwise, it returns the same String:

这里,getNonNullString() 方法是我们的辅助方法。它只是检查输入String对象的null引用。如果输入对象是null,它返回一个空的(“”)String,否则,它返回相同的String

return value == null ? "" : value;

However, as we know, String objects are immutable in Java. That means, every time we concatenate String objects using the + operator, it creates a new String in memory. So, using the + operator for concatenation turns out to be expensive.

然而,正如我们所知,String对象在Java中是不可变的。这意味着,每次我们使用+运算符连接String对象时,都会在内存中创建一个新的String。因此,使用+运算符进行连接会变成昂贵的

Additionally, we can use this approach of creating a helper method to check for null String objects in various other concatenation supporting operations. Let’s take a look at some of those.

此外,我们可以使用这种创建辅助方法的方法来检查其他各种支持连接操作的null String对象。让我们看一下其中的一些。

4. Using the String.concat() Method

4.使用String.concat() M方法

The String.concat() method is a good choice when we want to concatenate String objects.

String.conca()方法是我们想要连接String对象时的一个好选择。

Here, we can use our getNonNullString() method that checks for a null object and returns an empty String:

在这里,我们可以使用我们的getNonNullString()方法来检查null对象并返回一个空String

for (String value : values) {
    result = result.concat(getNonNullString(value));
}

The empty String returned by the getNonNullString() method gets concatenated to the result, thus ignoring the null objects.

getNonNullString()方法返回的空String被连接到结果,从而忽略了null对象。

5. Using the StringBuilder Class

5.使用StringBuilder

StringBuilder provides a bunch of useful and convenient String building methods. One of those is the append() method.

StringBuilder提供了一堆有用和方便的String构建方法。其中之一就是append()方法。

Here as well, we can use the same getNonNullString() method to avoid null objects while using the append() method:

在这里,我们也可以使用同样的getNonNullString()方法来避免null对象,同时使用append()方法。

for (String value : values) {
    result = result.append(getNonNullString(value));
}

6. Using the StringJoiner Class (Java 8+)

6.使用StringJoiner类(Java 8以上)

The StringJoiner class provides all the functionality of String.join() along with an option to start with a given prefix and end with a given suffix. We can use its add() method to concatenate the Strings.

StringJoiner类提供了String.join()的所有功能,以及一个以指定前缀开始,以指定后缀结束的选项我们可以使用它的add()方法来连接Strings。

As before, we can use our helper method getNonNullString() to avoid the null String values from getting concatenated:

和以前一样,我们可以使用我们的辅助方法getNonNullString()来避免nullString值被连接起来。

StringJoiner result = new StringJoiner("");

for (String value : values) {
    result = result.add(getNonNullString(value));
}

One difference between String.join() and StringJoiner is that unlike String.join(), we have to loop through the collection (Array, List, etc.) to join all the elements.

String.join()StringJoiner之间的一个区别是,与String.join()不同,我们必须在集合(Array, List,等)中循环,以连接所有元素。

7. Using Streams.filter (Java 8+)

7.使用Streams.filter(Java 8以上)

The Stream API provides a substantial number of sequential and parallel aggregate operations. One such intermediate stream operation is filter which accepts a Predicate as input and transforms the Stream into another Stream based on the given Predicate.

Stream API 提供了大量的顺序和并行聚合操作。其中一个中间流操作是过滤器,它接受Predicate作为输入,并基于给定的Predicate>将Stream转换为另一个Stream

So, we can define a Predicate that will check for the null value of a String and pass this Predicate to the filter() method. Consequently, the filter will filter out those null values from the original Stream.

因此,我们可以定义一个Predicate,它将检查Stringnull值,并将这个Predicate传递给filter() 方法。因此,过滤器将从原始的Stream.中过滤掉那些null值。

In the end, we can join all those non-null String values using Collectors.joining() and finally, collect the resultant Stream into a String variable:

最后,我们可以使用Collectors.join()将所有这些非nullString值连接起来,最后将结果Stream收集到一个String变量。

result = Stream.of(values).filter(value -> null != value).collect(Collectors.joining(""));

8. Conclusion

8.结语

In this article, we illustrated various approaches to avoid the concatenation of null String objects. There would always be more than one right approach to meet our requirements. So, we have to determine which approach fits the best at a given place.

在这篇文章中,我们说明了各种避免连接null String对象的方法。总是会有不止一种正确的方法来满足我们的要求。因此,我们必须确定哪种方法在特定的地方最适合。

We have to keep in mind that concatenating String itself could be an expensive operation, especially in loops. So, it’s always advisable to take into consideration the performance aspects of the Java String API.

我们必须牢记,连接String本身可能是一个昂贵的操作,尤其是在循环中。因此,我们总是建议考虑到Java String API的性能方面。

And as always, the code for these examples is available over on GitHub.

和往常一样,这些例子的代码可以在GitHub上找到