我有一个数组列表,我想把它完全输出为字符串。本质上,我想使用每个元素的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标准库的一个很好的补充。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- Printf与std::字符串?
- 在Jar文件中运行类
- 带参数的可运行?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- 如何在PHP中截断字符串最接近于一定数量的字符?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作