I have never found a neat(er) way of doing the following.
Say I have a list/array of strings.
abc
def
ghi
jkl
And I want to concatenate them into a single string delimited by a comma as follows:
abc,def,ghi,jkl
In Java, if I write something like this (pardon the syntax),
String[] list = new String[] {"abc","def","ghi","jkl"};
String str = null;
for (String s : list)
{
str = str + s + "," ;
}
System.out.println(str);
I'll get
abc,def,ghi,jkl, //Notice the comma in the end
So I have to rewrite the above for loop as follows
...
for (int i = 0; i < list.length; i++)
{
str = str + list[i];
if (i != list.length - 1)
{
str = str + ",";
}
}
...
Can this be done in a more elegant way in Java?
I would certainly use a StringBuilder/Buffer for efficiency, but I wanted to illustrate the case in point without being too verbose. By elegant, I mean a solution that avoids the ugly(?) if
check inside the loop.
There are several methods to perform concatenation operation: Using addAll() method. Using stream. Using union()
Using + Operator The + operator is one of the easiest ways to concatenate two strings in Java that is used by the vast majority of Java developers. We can also use it to concatenate the string with other data types such as an integer, long, etc.
concat will typically be the fastest way to concat two String s (but do note null s).
When concatenating three dynamic string values or less, use traditional string concatenation. When concatenating more than three dynamic string values, use StringBuilder . When building a big string from several string literals, use either the @ string literal or the inline + operator.
Using Guava's (formerly google-collections) joiner class:
Joiner.on(",").join(list)
Done.
Here is my version: Java Tricks: Fastest Way to Collecting Objects in a String
StringBuilder buffer = new StringBuilder ();
String delim = "";
for (Object o: list)
{
buffer.append (delim);
delim = ", "; // Avoid if(); assignment is very fast!
buffer.append (o);
}
buffer.toString ();
As an additional bonus: If your code in the loop is more complex, then this approach will produce a correct results without complex if()
s.
Also note that with modern CPUs, the assignment will happen only in the cache (or probably only in a register).
Conclusion: While this code looks odd at first glance, it has many advantages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With