将ArrayList中的多个元素放到一个数组中?

时间:2018-01-01 17:19:29

标签: java arrays sorting arraylist

需要一些帮助才能理解如何将ArrayList中的所有元素放到单个Array中。不确定是否可以在单个阵列中执行此操作。

声明

List componentNameList = new ArrayList(); 
String[] componentNameItem = soapApiCall.getComponentNames(); 
componentNameList.add(Arrays.toString(componentNameItem));

这是ArrayList的元素:

[[Index, Pattern, Smart, Intell][Index, Tree, Pet, Intel][Index, Pattern, Bear, Intell, Dog][Sky, Intern, Blond]]

数组的预期输出

<Index><Pattern><Smart><Intell><Index><Tree><Pet><Intel><Index><Pattern><Bear><Intell><Dog><Sky><Intern><Blond>

提前致谢。

1 个答案:

答案 0 :(得分:2)

首先,我建议你不要使用原始类型,我也不建议将数组的字符串表示添加到原始类型列表中。

因此,改变这个:

List componentNameList = new ArrayList();

到此:

List<List<String>> componentNameList = new ArrayList<>();

然后改变这个:

componentNameList.add(Arrays.toString(componentNameItem));

到此:

 componentNameList.add(new ArrayList<>(Arrays.asList(componentNameItem)));

然后你可以用下面的流来完成手头的任务:

String[] resultSet = componentNameList.stream() 
                                      .flatMap(List::stream) // flatten
                                      .toArray(String[]::new); // collect to array

然后打印:

 System.out.println(Arrays.toString(resultSet));