将值放入地图
Putting values into a Map
您好,我正在读取一个文件并将其解析为一个字符串和一个双精度值。
然后将解析后的值放入 ConcurrentHashMap 中。
(字符串是键,双精度是值)。
public class Test {
public static Map<String, Double> map = new ConcurrentHashMap<String, Double>();
public void readFromFile() throws IOException {
String text = "Hello.txt";
// Hello contains:
// HELLO 12312
// BYE 12213
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(text), Charset.forName("UTF-8")));
while ((text = reader.readLine()) != null) {
// Splits the read line in two where the space char is the
// separating
String[] stuff = text.split(" ");
map.put(stuff[0], Double.parseDouble(stuff[1]));
}
}
public static void main(String[] args) throws IOException {
Test t = new Test();
t.readFromFile();
System.out.println(map);
}
}
有人告诉我,这不是将文件中的值放入我的地图的好方法。
Hello.txt 有大约 400.000 个条目
所以我的两个问题:
为什么用这个方法不好?
我该如何改进它?
此外,如果这是使用 put 的完美方式,那么也请说明。
根据the answer from @irreputable,ConcurrentHashMap 的性能仅比HashMap 稍差。因此,除非此处的性能绝对至关重要,或者您确定不需要线程安全,否则您的实现非常好。
您好,我正在读取一个文件并将其解析为一个字符串和一个双精度值。
然后将解析后的值放入 ConcurrentHashMap 中。 (字符串是键,双精度是值)。
public class Test {
public static Map<String, Double> map = new ConcurrentHashMap<String, Double>();
public void readFromFile() throws IOException {
String text = "Hello.txt";
// Hello contains:
// HELLO 12312
// BYE 12213
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(text), Charset.forName("UTF-8")));
while ((text = reader.readLine()) != null) {
// Splits the read line in two where the space char is the
// separating
String[] stuff = text.split(" ");
map.put(stuff[0], Double.parseDouble(stuff[1]));
}
}
public static void main(String[] args) throws IOException {
Test t = new Test();
t.readFromFile();
System.out.println(map);
}
}
有人告诉我,这不是将文件中的值放入我的地图的好方法。 Hello.txt 有大约 400.000 个条目 所以我的两个问题:
为什么用这个方法不好?
我该如何改进它?
此外,如果这是使用 put 的完美方式,那么也请说明。
根据the answer from @irreputable,ConcurrentHashMap 的性能仅比HashMap 稍差。因此,除非此处的性能绝对至关重要,或者您确定不需要线程安全,否则您的实现非常好。