Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a list of strings into [duplicate]

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?

like image 686
user844541 Avatar asked May 25 '15 12:05

user844541


People also ask

How do I make a list of 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.

How do you print a list of elements in a new line?

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.

How do I combine a list of strings?

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.


2 Answers

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 " ".

like image 59
Boris the Spider Avatar answered Sep 21 '22 23:09

Boris the Spider


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, ") (") + ")";
like image 29
Sharon Ben Asher Avatar answered Sep 21 '22 23:09

Sharon Ben Asher