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


当前回答

在Java 8或更高版本中:

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

如果列表不是String类型,则可以使用连接收集器:

String listString = list.stream().map(Object::toString)
                        .collect(Collectors.joining(", "));

其他回答

到目前为止,这是一个相当古老的对话,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)。

在Java 8或更高版本中:

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

如果列表不是String类型,则可以使用连接收集器:

String listString = list.stream().map(Object::toString)
                        .collect(Collectors.joining(", "));

也许不是最好的方式,但却是优雅的方式。

Arrays.deepToString (arrays . aslist(“测试”,“Test2”)

import java.util.Arrays;

    public class Test {
        public static void main(String[] args) {
            System.out.println(Arrays.deepToString(Arrays.asList("Test", "Test2").toArray()));
        }
    }

输出

(测试,Test2)

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

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

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

如果您正在使用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的提交者。