如何将两个D字符串数组转换为一个D字符串数组?

时间:2018-11-02 03:57:20

标签: java arrays string

我有一个二维字符串数组:

String myTwoD[][] = {{"Apple", "Banana"}, {"Pork", "Beef"}, {"red", 
"green","blue","yellow"}};

如何在JAVA中将其转换为一维字符串数组:

OneD[]={"Apple", "Banana","Pork", "Beef","red", "green","blue","yellow"};

可以使用ArrayUtils吗?

这是数组的代码,我正在尝试将多页表列中的所有值存储到数组中以进行排序

for (i=0;i<pagecount; i++)
  {
  for (j=0;j<columncount;j++)
   {
    array[i][j]= t.getcolumnname().get(j).getText();
   }
  }

3 个答案:

答案 0 :(得分:2)

我发现的最简单的方法是使用流。

String myTwoD[][] = { { "Apple", "Banana" }, { "Pork", "Beef" }, { "red", "green", "blue", "yellow" } };
List<String[]> list = Arrays.asList(myTwoD);

list.stream().flatMap(num -> Stream.of(num)).forEach(System.out::println);

将结果存储到一维数组中。这样做:

String arr[] = list.stream().flatMap(num -> Stream.of(num)).toArray(String[]::new);

for (String s : arr) {
   System.out.println("Array is = " + s);
}

答案 1 :(得分:1)

有很多方法可以做到,一种方法是首先将2D数组的内容存储到列表中,然后使用它将元素存储在新的1D数组中。

在代码中看起来像这样:

//arr being your old array

    ArrayList<String> list = new ArrayList<String>();

    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {  
            list.add(arr[i][j]); 
        }
    }

    // now you need to add it to new array


    String[] newArray = new String[list.size()];
    for (int i = 0; i < newArray.length; i++) {
        newArray[i] = list.get(i);
    }

答案 2 :(得分:0)

尝试一下。

String myTwoD[][] = {{"Apple", "Banana"}, {"Pork", "Beef"},{"red", "green","blue","yellow"}};

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

    for (String[] oneDArray : myTwoD) { //loop throug rows only
        lt.addAll(Arrays.asList(oneDArray));
    }

    String[] oneDArray =(String[])lt.toArray(new String[0]); //conversion of list to array      
    System.out.println(Arrays.toString(oneDArray)); //code for printing array