Java 8:以数据的形式存储和检索数据table
Java 8: store and retrieve data in form of a data table
我想以数据 table 的形式存储数据,如下所示:
+--------+-------+-----+-----+
| | s1 | s2 | s3 |
+--------+-------+-----+-----+
| c1 | 5 | 7 | 7 |
+--------+-------+-----+-----+
| c2 | 1 | 6 | 9 |
+--------+-------+-----+-----+
| c3 | 0 | 9 | 6 |
+--------+-------+-----+-----+
将此存储在 java 中的好方法是什么,这样我就可以通过它们的键检索数据。
我需要一个如下所示的方法:
public int getData(String row, String column);
// Example:
int i = getData("c1", "s1") // Would return 5
解决这个问题的一种方法是使用这样的数据结构:
Map<String, Map<String, Integer>> map;
您可以使用 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
二维地图
Map<String, Map<String, Integer>> map;
public int getData(String row, String column) {
return map.get(row).get(column); // can lead to NullPointerException
}
或者你可以使用二维数组:
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];
}
第二种方法仅在 table 的结构不会经常更改并且您可以从字符串中解析出索引时才可行。
我想以数据 table 的形式存储数据,如下所示:
+--------+-------+-----+-----+
| | s1 | s2 | s3 |
+--------+-------+-----+-----+
| c1 | 5 | 7 | 7 |
+--------+-------+-----+-----+
| c2 | 1 | 6 | 9 |
+--------+-------+-----+-----+
| c3 | 0 | 9 | 6 |
+--------+-------+-----+-----+
将此存储在 java 中的好方法是什么,这样我就可以通过它们的键检索数据。
我需要一个如下所示的方法:
public int getData(String row, String column);
// Example:
int i = getData("c1", "s1") // Would return 5
解决这个问题的一种方法是使用这样的数据结构:
Map<String, Map<String, Integer>> map;
您可以使用 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
二维地图
Map<String, Map<String, Integer>> map;
public int getData(String row, String column) {
return map.get(row).get(column); // can lead to NullPointerException
}
或者你可以使用二维数组:
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];
}
第二种方法仅在 table 的结构不会经常更改并且您可以从字符串中解析出索引时才可行。