How to format a list of strings into
Solution 1
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 " ".
Solution 2
if you want a one-line solution, you could use one of the the StringUtils.join methods in Apache Commons Lang.
String result = "(" + StringUtils.join(myListOfStrings, ") (") + ")";
Solution 3
You can try this:
List<String> list = new ArrayList<String>();
list.add("str1");
list.add("str2");
list.add("str3");
for(String s : list) {
System.out.println(String.format(" (%s) ", s));
}
user844541
Updated on August 10, 2022Comments
-
user844541 almost 2 years
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?
-
Maroun almost 9 yearsAre you using Java 8?
-
Admin almost 9 yearsWell, StringBuilder seems obvious , can you provide an example of the code (using SB) so we better understand what you mean , please.
-
nilesh virkar almost 9 yearsYou can use StringBuilder(if you don't want thread safe) or use string buffer
-
Olimpiu POP almost 9 yearscan't you have a wrapper class for your list?
-
-
Boris the Spider almost 9 yearsThis is similar to my second alternative that is less efficient. Also, it doesn't look like the OP wants the output to be pre/sufffixed with spaces - you should join on a space as I did in my code.
-
Boris the Spider almost 9 yearsEugh - I don't like this at all. It mixes formatting with output is a very ugly way. It also should probably us
printf
rather than bothformat
andprint
. Or use amap
then aprint
. Either way, I think this isn't a good approach. -
guido almost 9 years@BoristheSpider (agree on the printf, yet-) it is much more readable than both the stream/map/collect and than the joining forms
-
guido almost 9 years@BoristheSpider did you ever use a logger at all?
-
Boris the Spider almost 9 yearsLogging if for debugging purposes not business logic.
-
Boris the Spider almost 9 yearsYour new code is much better, but I think that if you have a
StringBuilder
then use one - skip theformat
entirely and its overhead... -
guido almost 9 years@BoristheSpider I honestly don't see how decorating data like this could fit business logic; anyway, it is true that String.format introduces some overhead for this simple example (parsing the format pattern): but in general, it is used for his added features (locale) and because the OP asks to use it, hopefully for some good reason, I sticked to it. Again, if there is no specific requirement asking for best performance (in this case it was asking for elegance), I would not sacrifice readability for some micro-optimizing away some constant time.
-
DavidPostill almost 9 yearsCould you please edit your answer to give an explanation of why this code answers the question? Code-only answers are discouraged, because they don't teach the solution.