April 30, 2016
Java Two Dimensional String Array Iterator
Problem
Given the signature of the method below. It receives a two dimensional array of strings. Provide implementation that iterates through each string in each sub-array in the order they are provided but it skips null values
1 |
public static Iterator iterateStrings(String[]... stringArrays) |
Solution
We are dealing with a two dimensional array of strings so we need a proper way to loop through it. It is a common task in programming. You just fix the row then loop in the column if you want to process it row by row. The … here represents the rows and the [] represents the columns and the intersection is a given string that needs to be returned if not null.
- hasNext: as long as the row index is less than number of rows and column index is less than number of columns then there are elements to process
- next: loop in a two dimensional array of strings row by row
Here is the code to do that
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
public static class MyList implements Iterable { //Two dimensional array of strings private String[][] m_arr; //Construct list from a two dimensional array of strings public MyList(String[][] arr) { this.m_arr = arr; } @Override public Iterator iterator() { Iterator it = new Iterator() { //Array row and column indexes private int i = 0; private int j = 0; @Override //Has next as long as the indexes are not out of limit public boolean hasNext() { return i < m_arr.length && j < m_arr[i].length; } //Controlling the indexes of nested loops is //straightforward but in this case we are hacking //the index values because the return statement //exist the loop so we need to compensate for that private void resetIndexes() { if (j == m_arr[i].length) { j = 0; i++; } } @Override public String next() { //Check if (!hasNext()) return null; //Loop through the array: rows while (i < m_arr.length) { //Loop through the array: columns while (j < m_arr[i].length) { //Nulls are not allowed if (m_arr[i][j] != null) { //Save value because we need to modify indexes String str = m_arr[i][j]; //Increment now because the return will //exit the loop j++; //Reset j then increment i because the //return will exit the loop resetIndexes(); return str; } //If null move on else { j++; resetIndexes(); } } i++; } return null; } @Override public void remove() { //do nothing } }; return it; } } public static Iterator iterateStrings(String[]... stringArrays) { //Wrap the two dimensional array of strings in our custom built list MyList list = new MyList(stringArrays); return list.iterator(); } |