The article is continuously updated, you can follow the public programmer Alang or visit unread code blog .
This article Github.com/niumoo/JavaNotes has been included, welcome to Star.
1 Introduction
Java provides a variety of ways to concatenate String strings, but sometimes if we don't pay attention to the null
string, we may concatenate null
into the result, which is obviously not what we want.
In this article, I will introduce some ways to avoid the null
value when concatenating Strings.
<!-- more -->
2. Problem recurrence
If we want to concatenate String arrays, we can simply use the +
operator to concatenate, but we may encounter null
value.
String[] values = {"https", "://", "www.", "wdbyte", ".com", null};
String result = "";
for (String value : values) {
result = result + value;
}
This will concatenate all elements into the resulting string like this:
https://www.wdbyte.comnull
However, we have found the problem, the last null
value is also concatenated as a string, which is obviously not what we want.
Also, even if we run on Java 8 or higher and then use the String.join() ) static method to concatenate strings, we get output with the value null
.
String[] values = {"https", "://", "www.", "wdbyte", ".com", null};
String result = String.join("", values);
// output: https://www.wdbyte.comnull
Let's take a look at some methods to avoid null
value being spliced. My expected output should be:
https://www.wdbyte.com
3. Use the + operator
The addition symbol +
can splicing String strings, then we only need to judge null
during splicing to replace the null
value with an empty string.
for (String value : values) {
result = result + (value == null ? "" : value);
}
However, we know that String is an immutable object. Using the +
number will frequently create a string object, and each time a new string will be created in memory, so using the +
symbol to splicing strings is very expensive. .
In order to facilitate the subsequent code demonstration, we extract a method that can pass in a string and return a non-null string.
public String nullToString(String value) {
return value == null ? "" : value;
}
So the above code could instead call this method:
for (String value : values) {
result = result + nullToString(value);
}
4. Using String.concat()
String.concat()
) is a method that comes with the String class, and it is very convenient to use this method to splicing strings.
for (String value : values) {
result = result.concat(getNonNullString(value));
}
Because the nullToString()
method is called, there is no null
value in the result.
5. Using StringBuilder
The StringBuilder class provides many useful and convenient String construction methods. The most commonly used method is the append()
method, which uses append()
to splicing strings, and combines nullToString()
method to avoid null
value.
String[] values = {"https", "://", "www.", "wdbyte", ".com", null};
StringBuilder result = new StringBuilder();
for (String value : values) {
result = result.append(nullToString(value));
}
The following results can be obtained:
https://www.wdbyte.com
6. Using the StringJoiner class (Java 8+)
The StringJoiner class provides a more powerful string splicing function. It can not only specify the delimiter during splicing, but also specify the prefix and suffix during splicing. Here we can use its add()
method to splicing strings.
The same will use the nullToString()
method to avoid null
value.
String[] values = {"https", "://", "www.", "wdbyte", ".com", null};
StringJoiner result = new StringJoiner("");
for (String value : values) {
result = result.add(nullToString(value));
}
7. Using Streams.filter (Java 8+)
Stream API is a powerful stream operation class introduced in Java 8, which can perform common filtering, mapping, traversal, grouping, statistics and other operations. The filtering operation filter
can receive a Predicate function, and the Predicate function interface is the same as the Function (opens new window) interface, which is a functional interface, and it can accept a generic <T>
Boolean type , Predicate is often used for data filtering.
Therefore, we can define a Predicate to check for a string of null
and then pass it to the filter()
method of the Stream API.
Finally, use the Collectors.joining()
method to splice the remaining non- null
strings.
String[] values = {"https", "://", "www.", "wdbyte", ".com", null};
String result = Arrays.stream(values)
.filter(Objects::nonNull)
.collect(Collectors.joining());
8. Summary
This article introduces several ways to splicing non- null
strings. Different methods may be suitable for different scenarios, but it should be noted that splicing String strings is an expensive operation. The following is a benchmark test of several splicing methods using JMH the result of.
Benchmark Mode Cnt Score Error Units
StringConcat.operateAdd thrpt 25 13635005.992 ± 549759.774 ops/s
StringConcat.String.concat thrpt 25 7465193.417 ± 667928.552 ops/s
StringConcat.StringBuilder thrpt 25 13949781.608 ± 142001.421 ops/s
StringConcat.StringJoiner thrpt 25 9502405.473 ± 211977.433 ops/s
StringConcat.StreamFilter thrpt 25 8998396.107 ± 649033.722 ops/s
It can be seen that the performance of StringBuilder is the best, and the actual use should be combined with specific scenarios, and then choose the lowest performance overhead method.
As always, the code in the article is located at: github.com/niumoo/JavaNotes
subscription
You can search for programmer Alang or visit Unread Code Blog to read.
This article Github.com/niumoo/JavaNotes has been included, welcome to Star.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。