Java – Transpose arrays

Transpose arrays… here is a solution to the problem.

Transpose arrays

I’m reading a CSV file using the following code:

  String next[] = {};
  List<String[]> dataArray = new ArrayList<String[]>();

try {
      CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("inputFile.csv")));
      for(; ;) {
          next = reader.readNext();
          if(next != null) {
              dataArray.add(next);
          } else {
              break;
          }
      }
  } catch (IOException e) {
      e.printStackTrace();
  }

This converts the CSV file to the array “dataArray”. My app is a dictionary type app – the first column of input data is a list of words, and the second column is the definition of those words. The following is an example of loading an array:

Term 1, Definition 1
Term 2, Definition 2
Term 3, Definition 3

To access one of the strings in the array, I used the following code:

dataArray.get(rowNumber)[columnNumber]

However, I need to be able to generate a list of all terms so that they can be displayed for dictionary applications. As I understand it, accessing columns individually is much longer than accessing rows (I’m from a MATLAB background, it’s simple).

It seems that to be able to access any row of my input data at any time, I’d better transpose the data and read it that way; Namely:

Term 1, Term 2, Term3
Definition 1, Definition 2, Definition 3

Of course, I could just provide a CSV file that is pivoted first – but Excel or OO Calc don’t allow more than 256 rows, and my dictionary contains about 2000 terms.

Welcome to any of the following solutions:

  • A method of transposing an array after reading it in
  • Make changes to the code posted above to “pivot” the data
  • A simple way to read the entire column of an array as a whole

Solution

It might be better to use Map data structures such as HashMap:

String next[] = {};
HashMap<String, String> dataMap = new HashMap<String, String>();

try {
    CSVReader reader = new CSVReader(new InputStreamReader(getAssets().open("inputFile.csv")));
    for(; ;) {
        next = reader.readNext();
        if(next != null) {
            dataMap.put(next[0], next[1]);
        } else {
            break;
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

Then you can access the first column

dataMap.keySet();

The second column consists of

dataMap.values();

Note the assumption here that the first column of the input data is a unique value (that is, there are no duplicate values in the Term column).

To be able to access keys (terms) in array form, you can simply do the following:

String[] terms = new String[dataMap.keySet().size()];
terms = dataMap.keySet().toArray(terms);

Related Problems and Solutions