Reputation: 7145
I need a string as follows.
s = "$.vars.start.params.operations.values"
I've tried to write it like this:
String s = "$".concat(".").concat("start").concat(".").concat("params").concat(".").
concat("operations").concat(".").concat("values");
There's a chain of concat
operations.
Is there a better way of doing this?
Upvotes: 0
Views: 199
Reputation: 108971
Never ever use concat
like this. It is bound to be less efficient than the code the compiler generates when using +
. Even worse, the code as shown (using only String literals) would have been replaced with a single string literal at compile time if you had been using +
instead of concat
. There is almost never a good reason to use concat
(I don't believe I have ever used it, but maybe it could be useful as a method reference in a reduce operation).
In general, unless you are concatenating in a loop, simply using +
will get you the most (or at least relatively good) performant code. When you do have a loop, consider using a StringBuilder
.
Upvotes: 2
Reputation: 41
Do you have a reason for using .concat? In this case, you would approach this by using something like "$"+"..." etc.
If you wanted to add a dynamic approach, I would recommend using variables instead. It would look like
String s = variable1 + variable2 + variable;
If you are looking for something a bit more than there is also the String.join
Upvotes: 0
Reputation: 28978
It seems like you're looking for Java 8 method String.join(delimiter,elements)
, which expects a delimiter of type CharSequence
as the first argument and varargs of CharSequence
elements.
String s = String.join(".", "$", "vars", "start", "params", "operations", "values");
Upvotes: 1