将整数数组转换为单个字符串

Los*_*ity 2 java arrays type-conversion

我很难找到如何使用Java 8从Integer的arrayList轻松构建字符串,就像这样:

[3,22,1,5]至“ 3 22 1 5”

目前我尝试了:

List<Integer> ids = new ArrayList<Integer>();
/* ... */
String.join(" ", ((ArrayList<String>)(ids))); //cast do not work

List<Integer> ids = new ArrayList<Integer>();
/* ... */
String.join(" ", ids.forEach(id -> Integer.toString(id))); //forEach returns void so it throws an error
Run Code Online (Sandbox Code Playgroud)

任何人都有方便/优雅的解决方案吗?

谢谢大家,祝你有美好的一天

pur*_*eon 6

您可以使用流来执行此操作

List<Integer> ids = new ArrayList<Integer>();
/* ... */
String joined= ids.stream()
                   .map(i -> i.toString())
                   .collect(Collectors.joining(" "));
Run Code Online (Sandbox Code Playgroud)