java 如何将字符串列表格式化为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30438582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:07:18  来源:igfitidea点击:

How to format a list of strings into

javaliststring-formatting

提问by user844541

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:

我有一个字符串列表,我想以相同的方式格式化每个字符串。例如 myListOfStrings = str1、str2、str3,我的格式是 (%s) 我想要这样的东西:

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?

有没有一种优雅的方式来做到这一点?还是我必须使用字符串生成器并对所有字符串执行 foreach 循环?

回答by Boris the Spider

You can do this with Java 8:

你可以用 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

a) (b) (c)

Then you use the prefix and suffix arguments to joiningto with prefix with (and suffix with ), to produce the right outcome.

然后您使用前缀和后缀参数 to joiningwith 前缀(和后缀 with ),以产生正确的结果。

The second alternative transforms each item to ( + item + )and then joins them on " ".

第二个选择将每个项目转换为( + item + ),然后将它们连接到“”。

The first might also be somewhat faster, as it only requires the creation of oneStringBuilderinstance - for both the join and the pre/suffix. The second alternative requires the creation of n + 1StringBuilderinstances, one for each element and one for the join on " ".

第一个也可能稍微快一些,因为它只需要为连接和前/后缀创建一个StringBuilder实例。第二种选择需要创建n + 1 个StringBuilder实例,一个用于每个元素,一个用于连接“”。

回答by Krishanthy Mohanachandran

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

回答by Sharon Ben Asher

if you want a one-line solution, you could use one of the the StringUtils.joinmethods in Apache Commons Lang.

如果您想要一个单行解决方案,您可以使用Apache Commons Lang 中的StringUtils.join方法之一。

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

回答by guido

Using Java8 new forEachmethod for iterating over collections:

使用 Java8 新forEach方法迭代集合:

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

在这里试试:https: //ideone.com/52EKRH

回答by Kajo

Boris The Spider's answer is what I would go with, but in case you are not using java 8, but maybe you are using Guava you can do something like this, albeit it is a bit verbose:

Boris The Spider 的回答是我会采用的答案,但如果您没有使用 java 8,但也许您正在使用 Guava,您可以执行以下操作,尽管它有点冗长:

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

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

回答by G.B.Krishna

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