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


当前回答

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

其他回答

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

如果你碰巧在Android上,你还没有使用杰克(例如,因为它仍然缺乏支持即时运行),如果你想要更多的控制结果字符串的格式(例如,您想使用换行符分隔的元素),并使用/想使用StreamSupport库(在Java 7使用流或更早版本的编译器),你可以使用这样的(我把这个方法ListUtils类):

public static <T> String asString(List<T> list) {
    return StreamSupport.stream(list)
            .map(Object::toString)
            .collect(Collectors.joining("\n"));
}

当然,确保在列表对象的类上实现toString()。

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

只需使用StringBuilder,如下所示:

StringBuilder sb = new StringBuilder();

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

String finalString = sb.toString();

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

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

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

在Java 8中,这很简单。参见整数列表的示例:

String result = Arrays.asList(1,2,3).stream().map(Object::toString).reduce((t, u) -> t + "\t" + u).orElse("");

或者多行版本(更容易阅读):

String result = Arrays.asList(1,2,3).stream()
    .map(Object::toString)
    .reduce((t, u) -> t + "\t" + u)
    .orElse("");

更新-一个更短的版本

String result = Arrays.asList(1,2,3).stream()
                .map(Object::toString)
                .collect(Collectors.joining("\t"));