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


当前回答

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

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 list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = list.toString();
System.out.println("Step-1 : " + str);
str = str.replaceAll("[\\[\\]]", "");
System.out.println("Step-2 : " + str);

输出:

Step-1 : [1, 2, 3]
Step-2 : 1, 2, 3

在Java 8或更高版本中:

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

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

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

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

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

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)

下载Apache Commons Lang并使用该方法

 StringUtils.join(list)

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

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

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