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();
   }
  }
1
  • 3
    Arrays.stream(myTwoD).flatMap(Arrays::stream).toArray(String[]::new) Commented Nov 2, 2018 at 3:59

3 Answers 3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

9 Comments

I tried it but didn't work. Will this work for string? @PradyumanDixit
@SUPARNASOMAN try the updated code
It is showing null values in the array now @PradyumanDixit
Which array is showing null values? newArray must be having the values of your previous array.
Can you show the exact code you're using for this, right now, because this code is and should be working. I can look into your code and tell what may have gone wrong.
|
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.