使用字符串条件连接 For 循环中的字符串数组

Concatenating String Arrays in For Loops with String conditions

我目前是运行一个for循环,它读取一个List对象,然后将它们拆分成数组。这是示例代码:

List<String> lines = Arrays.asList("foo,foo,foo","bar,baz,foo","foo,baz,foo", "baz,baz,baz", "zab,baz,zab");
    for (String line : lines){
        String[] array = line.split(",");
        String[] arraySplit2 = array[0].split(",");
        System.out.print(Arrays.toString(arraySplit2));
    }

输出为:

[foo][bar][foo][baz][zab]

我希望在循环下将数组字符串连接成一个,以便显示:

[foo, bar, foo, baz, zab]

我遇到了一些麻烦,因为循环的条件阻止我使用 increase int i 技巧和使用 System.arraycopy()。我对改变循环本身的结构等想法持开放态度。

不能 100% 确定您想要什么,但我猜是这样的:

List<String> outList = new ArrayList<String>();
for (String line : lines) { 
    String[] array = line.split(",");
    outList.add(array[0]);
} 
String[] outStr = outList.toArray(new String[0]);
System.out.println(Arrays.toString(outStr));

您似乎试图用每行的第一个项目创建一个数组。

首先,需要先创建结果数组,行数大小:

String[] result = new String[lines.size()];
int index = 0;

不需要第二次拆分,在for循环中填充结果数组:

   result[index++] = array[0]

循环之后打印结果数组。