How to format a list of strings into

35,908

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));
}
Share:
35,908
user844541
Author by

user844541

Updated on August 10, 2022

Comments

  • user844541
    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
      Maroun almost 9 years
      Are you using Java 8?
    • Admin
      Admin almost 9 years
      Well, StringBuilder seems obvious , can you provide an example of the code (using SB) so we better understand what you mean , please.
    • nilesh virkar
      nilesh virkar almost 9 years
      You can use StringBuilder(if you don't want thread safe) or use string buffer
    • Olimpiu POP
      Olimpiu POP almost 9 years
      can't you have a wrapper class for your list?
  • Boris the Spider
    Boris the Spider almost 9 years
    This 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
    Boris the Spider almost 9 years
    Eugh - 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 both format and print. Or use a map then a print. Either way, I think this isn't a good approach.
  • guido
    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
    guido almost 9 years
    @BoristheSpider did you ever use a logger at all?
  • Boris the Spider
    Boris the Spider almost 9 years
    Logging if for debugging purposes not business logic.
  • Boris the Spider
    Boris the Spider almost 9 years
    Your new code is much better, but I think that if you have a StringBuilder then use one - skip the format entirely and its overhead...
  • guido
    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
    DavidPostill almost 9 years
    Could 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.