我有一个包含 42,000 行的 csv 文件,格式如下
03055,Milford,NH
03057,Mont Vernon,NH
03060,Nashua,NH
我尝试使用邮政编码作为键将数据存储在 HashMap
中,例如
while ((line = stream_in.readLine())!=null) {
LocationBean temp_location_bean = new LocationBean();
String line_trimmed = line.trim();
String[] line_chunked = line_trimmed.split(",",4);
temp_location_bean.setZip_code(line_chunked[0]);
temp_location_bean.setCity(line_chunked[1]);
temp_location_bean.setState(line_chunked[2]);
this.locations_as_beans_list.put(zip_code, temp_location_bean);
}
但是当我去查找时:
for(Map.Entry<String, LocationBean> location_object : this.locations_as_beans_list.entrySet())
{
LocationBean temp_location_bean = location_object.getValue();
if (params[0].matches(temp_location_bean.getZip_code())) {
master_location = temp_location_bean.getCity() + ","
+ temp_location_bean.getState()
+ ", (" + temp_location_bean.getZip_code() +")";
}
}
需要20多秒....性能不是应该比较快吗?我怎样才能提高这里的性能?
长话短说 如何优化此示例中的读取?
最佳答案
如果您正在寻找性能,那么您不应该迭代 entrySet
来查找键控邮政编码。相反,您可以使用 HashMap
并通过其键获取值。喜欢,
LocationBean temp_location_bean = this.locations_as_beans_list.get(params[0]);
if (temp_location_bean != null) {
master_location = temp_location_bean.getCity() + ","
+ temp_location_bean.getState()
+ ", (" + temp_location_bean.getZip_code() +")";
}
关于java - 我怎样才能用 42,000 个键优化这个 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30090617/