Skip to content

Instantly share code, notes, and snippets.

@NathanWA
Created June 29, 2019 20:53
Show Gist options
  • Save NathanWA/c202e98b354b9cf0001f5edced19f805 to your computer and use it in GitHub Desktop.
Save NathanWA/c202e98b354b9cf0001f5edced19f805 to your computer and use it in GitHub Desktop.
Flattening a string array
public class ArrayFlattener {
/**
*
* @param array containing objects of type String and/or array
* @return
*/
public static String [] flattenArray(Object [] array)
{
ArrayList<String> result = new ArrayList<String>();
extractInto(result,array);
//we need this to return an array of the correct type.
String [] strTemplate = new String[1];
return result.toArray(strTemplate);
}
/**
* Recursive function that adds all strings found to the destina
* @param destination ArrayList of strings - will be appended to
* @param array Containing Strings and arrays to extract
*/
private static void extractInto(ArrayList<String> destination, Object [] array)
{
for(Object o:array)
{
if(o instanceof String)
destination.add((String)o);
else if(o instanceof Object[])
extractInto(destination,(Object[])o);
}
}
}
public class ArrayFlattenerUnitTest {
final int SIZEOFARRAY = 18;
@Test
public void testComplexSolution()
{
//create a multilevel array hierarchy with number strings in order
Object [] array = {new Object[]{"0"},"1",new Object[] {"2","3"},"4",new Object[] {new Object[] {"5"},new Object []{new Object[] {"6"},"7",new Object[] {"8","9"}},"10"},"11",
new Object[] {new Object[] {new Object[]{"12","13",new Object[] {"14"}},new Object[] {"15", new Object[]{"16","17"}}}} };
Object [] result = ArrayFlattener.flattenArray(array);
//the result should be the number strings in order
for (int i=0; i<SIZEOFARRAY; i++)
{
Assert.assertEquals(String.valueOf(i), result[i]);
}
//code coverage of this test is 100%!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment