0

I have a two dimensional string array:

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

How do I convert this to a one dimensional string array as follows in JAVA:

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

Can ArrayUtils be used for this?

Here is the code for my array, I am trying to store all values in a multipage table column to an array for sorting

for (i=0;i<pagecount; i++)
  {
  for (j=0;j<columncount;j++)
   {
    array[i][j]= t.getcolumnname().get(j).getText();
   }
  }
SUPARNA SOMAN
  • 2,311
  • 3
  • 19
  • 35

3 Answers3

2

The simplest way I found out is using stream.

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);

To store the result into a 1D array. Do this:

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

for (String s : arr) {
   System.out.println("Array is = " + s);
}
AsthaUndefined
  • 1,111
  • 1
  • 11
  • 24
1

There are numerous ways of how you can do it, one way can be first storing the contents of your 2D array to a list and then using it to store the elements in your new 1D array.

In code it looks something like this:

//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);
    }
PradyumanDixit
  • 2,372
  • 2
  • 12
  • 20
0

try this.

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
Deepesh kumar Gupta
  • 884
  • 2
  • 11
  • 29