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?
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by space use sep=”\n” or sep=”, ” respectively.
You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.
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 " ".
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, ") (") + ")";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With