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?
source to share
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 "".
source to share
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, ") (") + ")";
source to share
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
source to share
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);
}
}));
source to share