How to format a list of strings in

I have a list of strings that I want to format each one the same way. e.g. myListOfStrings = str1, str2, str3 and my format (% s) I want to have something like this:

String.format(" (%s) ", myListOfStrings)

      

Will output

(str1)  (str2)  (str3)

      

Is there an elegant way to do this? or do I need to use a string builder and make a foreach loop on all lines?

+3


source to share


6 answers


You can do it 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 one connects the elements to ) (

, which gives:

a) (b) (c

Then you use the prefix and suffix arguments joining

with the prefix (

and the c suffix )

to get the correct result.

The second alternative converts each element to ( + item + )

and then concatenates them to "".

The former can also be slightly faster as it only requires one StringBuilder

instance to be instantiated - both for the concatenation and for the pre / suffix. The second option requires n + 1 instances to be instantiated StringBuilder

, one for each element and the other to connect to "".

+6


source


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));
}

      

+1


source


If you want a one-line solution, you can use one of the StringUtils.join methods in Apache Commons Lang.

String result = "(" + StringUtils.join(myListOfStrings, ") (") + ")";

      

+1


source


String strOut = "";
for(int i=0; i< myListOfStrings.size(); i++){
    strOut = strOut +"("+myListOfStrings.get(i)+")";
}

      

0


source


Using Java8 new forEach

method to iterate over collections:

public static String format(List<String> list) {
    StringBuilder sb = new StringBuilder();
    list.forEach(x -> sb.append(String.format(" (%s) ", x)));
    return sb.toString();
} 

      

Try it here: https://ideone.com/52EKRH

0


source


Boris. Spider's answer is what I would go with, but if you are not using java 8, but perhaps you are using Guava, you can do something like this, although this is a little verbose:

Joiner.on("").join(Collections2.transform(myListOfStrings, new Function<String, String>() {

        @Override
        public String apply(String input) {
            return String.format(" (%s) ", input);
        }
    }));

      

0


source







All Articles