我有一个数组列表,我想把它完全输出为字符串。本质上,我想使用每个元素的toString按顺序输出它,每个元素由制表符分隔。有什么快速的方法吗?你可以循环遍历它(或删除每个元素),并将它连接到一个字符串,但我认为这将是非常缓慢的。


当前回答

List<String> stringList = getMyListOfStrings();
StringJoiner sj = new StringJoiner(" ");
stringList.stream().forEach(e -> sj.add(e));
String spaceSeparated = sj.toString()

您将希望用作分隔符的字符序列传递给新的StringJoiner。如果你想做一个CSV: new StringJoiner(", ");

其他回答

如果你碰巧在Android上做这个,有一个很好的实用工具叫做TextUtils,它有一个.join(字符串分隔符,Iterable)方法。

List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
String joined = TextUtils.join(", ", list);

显然在Android之外没有太多用处,但我想把它添加到这个线程中…

如果您正在使用Eclipse Collections,则可以使用makeString()方法。

ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");

Assert.assertEquals(
    "one\ttwo\tthree",
    ArrayListAdapter.adapt(list).makeString("\t"));

如果可以将数组列表转换为FastList,就可以摆脱适配器。

Assert.assertEquals(
    "one\ttwo\tthree",
    FastList.newListWith("one", "two", "three").makeString("\t"));

注意:我是Eclipse Collections的提交者。

我看到相当多的例子依赖于额外的资源,但似乎这将是最简单的解决方案:(这是我在我自己的项目中使用的)这基本上只是从一个数组列表转换到一个数组,然后再转换到一个列表。

    List<Account> accounts = new ArrayList<>();

   public String accountList() 
   {
      Account[] listingArray = accounts.toArray(new Account[accounts.size()]);
      String listingString = Arrays.toString(listingArray);
      return listingString;
   }

到目前为止,这是一个相当古老的对话,apache commons现在在内部使用StringBuilder: http://commons.apache.org/lang/api/src-html/org/apache/commons/lang/StringUtils.html#line.3045

正如我们所知,这将提高性能,但如果性能是至关重要的,那么所使用的方法可能有些低效。尽管接口是灵活的,并且允许在不同的Collection类型之间保持一致的行为,但对于list(原始问题中的Collection类型)来说有些低效。

我这样做的基础是,我们会产生一些开销,这是我们可以通过简单地遍历传统for循环中的元素来避免的。相反,有一些额外的事情在幕后发生,检查并发修改、方法调用等。另一方面,增强的for循环将导致相同的开销,因为迭代器用于Iterable对象(List)。

这是一个O(n)算法(除非你做了一些多线程解决方案,你把列表分解成多个子列表,但我不认为这是你想要的)。

只需使用StringBuilder,如下所示:

StringBuilder sb = new StringBuilder();

for (Object obj : list) {
  sb.append(obj.toString());
  sb.append("\t");
}

String finalString = sb.toString();

StringBuilder将比字符串连接快得多,因为您不会在每个连接上重新实例化一个string对象。