I have a list of strings that I want to format each of them in the same way. e.g. myListOfStrings = str1, str2, str3, and my format is (%s) I want to have something like this:
String.format(" (%s) ", myListOfStrings)
Will output
(str1) (str2) (str3)
Is there an elegant way of doing this? or do I have to use a string builder and do a foreach loop on all the strings?
You can do this with Java 8:
import static java.util.stream.Collectors.joining;
public static void main(String[] args) throws Exception {
final List<String> strings = Arrays.asList("a", "b", "c");
final String joined = strings.stream()
.collect(joining(") (", "(", ")"));
System.out.println(joined);
}
Or:
final String joined = strings.stream()
.map(item -> "(" + item + ")")
.collect(joining(" "));
Which one you prefer is a matter of personal preference.
The first joins the items on ) (
which gives:
a) (b) (c
Then you use the prefix and suffix arguments to joining
to with prefix with (
and suffix with )
, to produce the right outcome.
The second alternative transforms each item to ( + item + )
and then joins them on " ".
The first might also be somewhat faster, as it only requires the creation of one StringBuilder
instance - for both the join and the pre/suffix. The second alternative requires the creation of n + 1 StringBuilder
instances, one for each element and one for the join on " ".