Skip to content

Instantly share code, notes, and snippets.

@asanand3
Created April 6, 2016 13:07
Show Gist options
  • Save asanand3/017f944299ebe6623b784d5d11a6602a to your computer and use it in GitHub Desktop.
Save asanand3/017f944299ebe6623b784d5d11a6602a to your computer and use it in GitHub Desktop.
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FlattenArray {
public static void main(String[] args) {
Integer[][] testArray = {
{
1, 2, 3
},
{
1, 2, 5
},
{
1, 5, 3, 6
}
};
for (Integer i : flattenInputArray(testArray)) {
System.out.print(i);
}
}
public static Integer[] flattenInputArray(Object[] inputArray) throws IllegalArgumentException {
if (inputArray == null)
return null;
List<Integer> list = new ArrayList<Integer>();
for (Object element : inputArray) {
if (element instanceof Integer) {
list.add((Integer) element);
}
else if (element instanceof Object[]) {
list.addAll(Arrays.asList(flattenInputArray((Object[]) element)));
}
else {
throw new IllegalArgumentException("InputArray is not valid");
}
}
return list.toArray(new Integer[list.size()]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment