Search code examples
javadatatablejava-8store

Java 8: store and retrieve data in form of a data table


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

Solution

  • 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