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?
CodePudding user response:
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, 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.
CodePudding user response:
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");
