9. Joining multiple strings with a delimiter

There are several solutions that fit well and solve this problem. Before Java 8, a convenient approach relied on StringBuilder, as follows:

public static String joinByDelimiter(char delimiter, String...args) {

StringBuilder result = new StringBuilder();

int i = 0;
for (i = 0; i < args.length - 1; i++) {
result.append(args[i]).append(delimiter);
}
result.append(args[i]);

return result.toString();
}

Starting with Java 8, there are at least three more solutions to this problem. One of these solutions relies on the StringJoiner utility class. This class can be used to construct a sequence of characters separated by a delimiter (for example, a comma).

It supports an optional prefix and suffix as well (ignored here):

public static String joinByDelimiter(char delimiter, String...args) {
StringJoiner joiner = new StringJoiner(String.valueOf(delimiter));

for (String arg: args) {
joiner.add(arg);
}

return joiner.toString();
}

Another solution relies on the String.join() method. This method was introduced in Java 8 and comes in two flavors:

String join​(CharSequence delimiter, CharSequence... elems)
String join​(CharSequence delimiter,
Iterable<? extends CharSequence> elems)

An example of joining several strings delimited by a space is as follows:

String result = String.join(" ", "how", "are", "you"); // how are you

Going further, Java 8 streams and Collectors.joining() can be useful as well:

public static String joinByDelimiter(char delimiter, String...args) {
return Arrays.stream(args, 0, args.length)
.collect(Collectors.joining(String.valueOf(delimiter)));
}
Pay attention to concatenating strings via the += operator, and the concat() and String.format() methods. These can be used to join several strings, but they are prone to performance penalties. For example, the following code relies on += and is much slower than relying on StringBuilder :

String str = "";
for(int i = 0; i < 1_000_000; i++) {
  str += "x";
}

+= is appended to a string and reconstructs a new string, and that costs time.

For third-party library support, please consider Apache Commons Lang, StringUtils.join()and Guava, Joiner.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.239.226