【问题标题】:Creating a proper string representation of a collection [duplicate]创建集合的正确字符串表示[重复]
【发布时间】:2015-11-03 13:08:33
【问题描述】:

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

示例:

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 循环对数组进行索引或做许多其他事情。

问题

将字符串列表转换为表示用一个逗号,并处理边缘情况在开头或结尾(意味着在第一个元素之前或最后一个元素之后没有逗号)?

【问题讨论】:

  • 如果您使用的是 Java 8,请查看 StringJoiner。
  • 谢谢@KevinEsche...我确实环顾四周,但没有找到您指出的问题,是的,这涵盖了我所问的很多问题。
  • @JonSkeet 我会用Java 8,我去看看StringJoiner,没听说过,谢谢

标签: java arrays string tostring stringbuilder


【解决方案1】:

使用 Java 8,您可以:

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

【讨论】:

  • String.join() 执行相同的操作StringJoiner sj=new StringJoiner(","); for(String i:list){ sj.add(i); } System.out.println(sj.toString());
  • 当列表是一个集合而不是 String[] 时,这将起作用
  • @MaulikShah 你测试了吗?
  • @Amila 不需要这样的编辑。 String.join 适用于数组:ideone.com/mKSIj8 因此您的编辑添加了更多不必要的工作,这是错误的。
  • join 的唯一问题是它支持 CharSequence 的集合或数组(如字符串),而不支持其他非文本类型。
【解决方案2】:

我认为最易读的应该是:

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

输出

[foo, bar, lorem, dolar]

【讨论】:

    【解决方案3】:

    使用Java8使用

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

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

    【讨论】:

    • map(o -&gt; o.toString()) 是不必要的,因为我们已经在处理 String 元素,而且 u + "," + t 效率非常低,因为每次它都必须创建新的 String ,这将是 old one 加上 new part 的副本。您应该改用 StringBuilder/StringJoiner 并将新部分附加到它,或者因为我们使用 stream,所以只需使用 collect(Collectors.joining(delimiter)) 而不是 reduce。
    【解决方案4】:

    您可能喜欢使用 Apache Commons 的 join

    公共静态字符串连接(可迭代迭代, 字符分隔符) 将提供的 Iterable 的元素连接到包含提供的元素的单个字符串中。 列表前后不加分隔符。迭代中的空对象或空字符串由空字符串表示。 请参阅此处的示例:join(Object[],char)。 参数: iterable - 提供要连接在一起的值的 Iterable,可以为 null separator - 要使用的分隔符 回报: 连接的字符串,如果为空迭代器输入则为空

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

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

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

    【讨论】:

      【解决方案5】:

      你可以试试这个方法

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

      【讨论】:

        【解决方案6】:

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

        应用于列表的 toString 函数返回类似

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

        这里你只需要用substring函数删除第一个和最后一个字符'['和']'。

        result = "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);
        

        【讨论】:

          【解决方案7】:

          在 java8 中使用流:

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

          【讨论】:

            【解决方案8】:

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

            另一个类似的问答here

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2017-05-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多