1

I'd like store data in form of a data table, which looks like this:

+--------+-------+-----+-----+
|        |   s1  |  s2 |  s3 |
+--------+-------+-----+-----+
|   c1   |   5   |  7  |  7  |
+--------+-------+-----+-----+
|   c2   |   1   |  6  |  9  |
+--------+-------+-----+-----+
|   c3   |   0   |  9  |  6  |
+--------+-------+-----+-----+

What is a good way to store this in java, so that I can retrieve the data by their keys.

I need a method which looks like this:

public int getData(String row, String column);

// Example:
int i = getData("c1", "s1") // Would return 5
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Nibor
  • 587
  • 1
  • 6
  • 16

3 Answers3

6

You can use Guava

https://github.com/google/guava/wiki/NewCollectionTypesExplained#table

Table<String, String, Integer> records = HashBasedTable.create();
records.put("s1","c1",5);
records.put("s3", "c3", 6);

Integer val = records.get("s1","c1"); // val = 5
aclowkay
  • 3,079
  • 4
  • 29
  • 59
1

One way to solve that is with a data structure like this:

Map<String, Map<String, Integer>> map;
pringi
  • 3,149
  • 5
  • 31
  • 39
0

Either a two dimensional Map

Map<String, Map<String, Integer>> map;

public int getData(String row, String column) {
    return map.get(row).get(column); // can lead to NullPointerException
}

or you can use a two dimensional array:

int[][] array = new int[10][12];

public int getData(String row, String column) {
    int x = ...; // get index from string
    int y = ...; // get index from string
    return array[x][y];
}

The second approach is only viable if the structure of the table does not change too often and if you can parse the index out of the strings.

Franziskus Karsunke
  • 4,710
  • 3
  • 38
  • 53