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


当前回答

下载Apache Commons Lang并使用该方法

 StringUtils.join(list)

 StringUtils.join(list, ", ") // 2nd param is the separator.

当然,您可以自己实现它,但是它们的代码经过了充分的测试,可能是最好的实现。

我是Apache Commons库的忠实粉丝,我也认为它是对Java标准库的一个很好的补充。

其他回答

在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"));

处理尾随分隔符的一种优雅方法是使用类分隔符

StringBuilder buf = new StringBuilder();
Separator sep = new Separator("\t");
for (String each: list) buf.append(sep).append(each);
String s = buf.toString();

类分隔符的toString方法返回分隔符,除了第一次调用。因此,在打印列表时,不需要前面的分隔符(在本例中是这样)。

将List更改为可读且有意义的String确实是每个人都可能遇到的一个常见问题。

案例1。如果你有apache的StringUtils在你的类路径(从rogerdpack和Ravi Wallau):

import org.apache.commons.lang3.StringUtils;
String str = StringUtils.join(myList);

情况2。如果你只想使用JDK(7)中的方法:

import java.util.Arrays;
String str = Arrays.toString(myList.toArray()); 

只是永远不要自己建造轮子,不要使用循环这一行任务。

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

对于使用制表符而不是使用println进行分离,您可以使用print

ArrayList<String> mylist = new ArrayList<String>();

mylist.add("C Programming");
mylist.add("Java");
mylist.add("C++");
mylist.add("Perl");
mylist.add("Python");

for (String each : mylist)
{       
    System.out.print(each);
    System.out.print("\t");
}