Skip to content

Instantly share code, notes, and snippets.

@vipulshah2010
Last active September 16, 2015 04:32
Show Gist options
  • Save vipulshah2010/b58cce7a3aaf2a346be9 to your computer and use it in GitHub Desktop.
Save vipulshah2010/b58cce7a3aaf2a346be9 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
/**
* This class contains various methods for manipulating arrays
*
* @author Vipul Shah
*/
public class FlattenArrayConverter {
/**
*
* @param objects Array of Objects which needs to be flatten
* @return flatten array of objects
*/
public static Object[] flattenArray(Object[] objects) {
if(objects == null){
return null;
}
List<Object> outputList = new LinkedList<>();
for (Object i : objects) {
if(i!=null) {
if (i instanceof Object[]) {
outputList.addAll(asListFromArray(flattenArray((Object[]) i)));
} else {
outputList.add(i);
}
}
}
return toArrayFromList(outputList);
}
/**
*
* @param objectArray target Array which needs to be converted into {@link List}
* @return list of items from array
*/
private static List<Object> asListFromArray(Object[] objectArray){
if(objectArray==null)
return null;
return Arrays.asList(objectArray);
}
/**
*
* @param objectList target {@link List} which needs to be converted into Array
* @return array of items from list
*/
private static Object[] toArrayFromList(List<Object> objectList){
if(objectList==null)
return null;
return objectList.toArray(new Object[objectList.size()]);
}
}
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
@Test
public void flattenTest() {
Object[] integerArray1 = {1};
Object[] integerArray2 = {new Object[]{1}, 2};
Object[] integerArray3 = {new Object[]{new Object[]{1}, 2}, 3};
Object[] integerArray4 = {new Object[]{new Object[]{new Object[]{1}, 2}, 3}, 4};
Object[] integerArray5 = {new Object[]{new Object[]{null, 2}, 3}, 4};
Assert.assertTrue(Arrays.equals(null, FlattenArrayConverter.flattenArray(null)));
Assert.assertTrue(Arrays.equals(new Object[]{1}, FlattenArrayConverter.flattenArray(integerArray1)));
Assert.assertTrue(Arrays.equals(new Object[]{1, 2}, FlattenArrayConverter.flattenArray(integerArray2)));
Assert.assertTrue(Arrays.equals(new Object[]{1, 2, 3}, FlattenArrayConverter.flattenArray(integerArray3)));
Assert.assertTrue(Arrays.equals(new Object[]{1, 2, 3, 4}, FlattenArrayConverter.flattenArray(integerArray4)));
Assert.assertTrue(Arrays.equals(new Object[]{2, 3, 4}, FlattenArrayConverter.flattenArray(integerArray5)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment