创建集合的适当字符串表示

Creating a proper string representation of a collection

我经常遇到创建对象集合的字符串表示形式的任务。

示例:

String[] collection = {"foo", "bar", "lorem", "dolar"};

我要创建的表示:"foo, bar, lorem, dolar".

每次我遇到这个任务时,我都想知道哪种方法是达到预期结果的最干净、最方便的方法..

我知道有很多方法可以获得所需的表示,但例如我一直想知道,是否有可能仅使用 for/each 循环来创建字符串?

像这样:

StringBuilder builder = new StringBuilder();

for (String tag : list) {
  builder.append(tag + ", ");

String representation = builder.toString();
// but now the String look like this: "foo, bar, lorem, dolar, " which nobody wants

或者最好直接使用迭代器吗?

假设列表是一个集合(他们在 JDK 中就是这样做的):

Iterator<String> it = list.iterator();
while (it.hasNext()) {
  sb.append(it.next());
  if (!it.hasNext()) {
    break;
  }
  sb.append(", ");
}

当然可以使用传统的 for 循环对数组进行索引或做许多其他事情。

问题

什么是最简单/最佳可读性/最安全转换列表的方法字符串到表示 用逗号分隔每个元素 ,并且 在开头或结尾处理边缘情况 (意味着之前没有逗号第一个元素或最后一个元素之后)?

你可以这样试试

String[] collection = {"foo", "bar", "lorem", "dolar"};    
StringBuilder sb=new StringBuilder();
for(String i:collection){
   sb.append(i);
   sb.append(",");
}
sb.replace(sb.lastIndexOf(","),sb.lastIndexOf(",")+1,"");
System.out.println(sb.toString());

输出:

foo,bar,lorem,dolar

Java8中可以尝试如下

 String[] collection = {"foo", "bar", "lorem", "dolar"};   
 StringJoiner sj=new StringJoiner(",");
 for(String i:collection){
    sj.add(i);
 }
 System.out.println(sj.toString());

使用 Java 8,您可以:

String listJoined = String.join(",", list);

您可能喜欢使用 Apache Commons 的 join

public static String join(Iterable iterable, char separator) Joins the elements of the provided Iterable into a single String containing the provided elements. No delimiter is added before or after the list. Null objects or empty strings within the iteration are represented by empty strings. See the examples here: join(Object[],char). Parameters: iterable - the Iterable providing the values to join together, may be null separator - the separator character to use Returns: the joined String, null if null iterator input

它已经在一个流行的 utils 包中实现,并完全执行您在代码中所做的事情。

作为替代实现,仅供讨论,您可能希望在每次迭代时将逗号附加到字符串缓冲区,但在返回字符串时跳过最后一个字符

Iterator<String> it = list.iterator();
while (it.hasNext()) {
  sb.append(it.next());
  sb.append(", ");
}
return sb.substring(0,sb.length()-1);

使用Java8 使用

String joined = Stream.of(collection)
                    //.map(Object::toString) //for non-String elements
                      .collect(Collectors.joining(","));

以获得所需的结果或上面传播的 String.join。

我认为最易读的是:

String[] collection = {"foo", "bar", "lorem", "dolar"};
String s = Arrays.asList(collection).toString();
System.out.println(s);

输出

[foo, bar, lorem, dolar]

您可以使用 Arrays.asList 函数将数组转换为 List 对象。

应用于列表的 toString 函数 returns 类似于

stringCollection = "[foo, bar, lorem, dolar]"

这里只需要用substring函数去掉第一个和最后一个字符'['和']'即可

结果 = "foo, bar, lorem, dolar"

//This is your String array
String[] collection = {"foo", "bar", "lorem", "dolar"};
//You convert it to a List and apply toString
String stringCollection = Arrays.asList(collection).toString(); 
//Remove the '[' and  ']' fromt the resulted String 
String result = stringCollection.substring(1, stringCollection.length()-1);

在 java8 中使用流:

String[] collection = {"foo", "bar", "lorem", "dolar"};    
String output = Arrays.asList(collection ).stream().collect(Collectors.joining(", "));

使用 Apache 的通用语言:StringUtils.join(collection , ',');

另一个类似的问答here