【发布时间】:2020-10-28 03:22:27
【问题描述】:
我正在尝试读取文本文件并使用哈希图进行存储。该文件包含如下信息:
1946-01-12;13:00:00;0.3;G
1946-01-12;18:00:00;-2.8;G
1946-01-13;07:00:00;-6.2;G
1946-01-13;13:00:00;-4.7;G
1946-01-13;18:00:00;-4.3;G
1946-01-14;07:00:00;-1.5;G
1946-01-14;13:00:00;-0.2;G
我想将日期存储为键,然后将“13:00:00;0.3;G”作为值存储,其中 13:00 是时间,0.3 是温度,G 代表质量代码。我想知道这是否可能,因为文件中的许多行具有相同的日期?我已经编写了将数据存储在列表中的代码,但现在我想将其存储在地图中。我的旧代码如下所示:
/**
* Provides methods to retrieve temperature data from a weather station file.
*/
public class WeatherDataHandler {
private List<Weather> weatherData = new ArrayList<>();
public void loadData(String filePath) throws IOException {
List<String> fileData = Files.readAllLines(Paths.get("filepath"));
for(String str : fileData) {
List<String> parsed = parseData(str);
LocalDate date = LocalDate.parse(parsed.get(0));
LocalTime time = LocalTime.parse(parsed.get(1));
double temperature = Double.parseDouble(parsed.get(2));
String quality = parsed.get(3);
//new Weather object
Weather weather = new Weather(date, time, temperature, quality);
weatherData.add(weather);
}
}
private List<String> parseData(String s) {
return Arrays.asList(s.split(";"));
}
我在实现 hashmap 时卡住了。我从下面的一些代码开始,但我不知道如何循环一系列日期。将文件中的数据存储在地图中的最简单方法是什么?
public class WeatherDataHandler {
public void loadData(String filePath) throws IOException {
Map<LocalDate, String> map =new HashMap<LocalDate, String>();
BufferedReader br = new BufferedReader(new FileReader("filepath"));
String line="";
int i=0;
while (line != null) {
line = br.readLine();
map.put(i,line);
i++;
}
String date="";
String time="";
String temperature="";
String quality="";
for(int j=0;j<map.size();j++){
if(!(map.get(j)== null)){
String[] getData=map.get(j).toString().split("\\,");
date = getData[0];
time = getData[1];
temperature = getData[2];
quality = getData[3];
}
}
}
【问题讨论】:
-
正如你所说,使用日期作为键是行不通的,因为会有重复。但是,如果您不介意语义上的变化,您可以考虑统一日期和时间(并可能将其转换为日期对象),然后将其用作键。
标签: java data-structures hashmap storing-data