将值放入Map中

时间:2015-12-07 09:35:41

标签: java parsing hashmap bufferedreader

您好我正在读取文件并将其解析为String和Double。

然后将解析后的值放入ConcurrentHashMap。 (String是Key,Double是Value)。

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的完美方式,那么请同样说明。

1 个答案:

答案 0 :(得分:1)

根据the answer from @irreputable,ConcurrentHashMap的性能仅略差于HashMap。因此,除非这里的性能绝对至关重要,或者您确定不需要线程安全,否则您的实现完全没问题。

相关问题