【问题标题】:Putting values into a Map将值放入 M​​ap
【发布时间】:2016-03-11 20:47:24
【问题描述】:

您好,我正在读取文件并将其解析为字符串和双精度。

然后将解析后的值放入 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);

    }
}

有人告诉我,这不是将值从 File 放入我的 Map 的好方法。 Hello.txt 有大约 400.000 个条目 所以我的两个问题:

为什么用这种方法不好?

我该如何改进它?

另外,如果这是一个非常好的使用 put 的方式,那么也请这样说。

【问题讨论】:

  • 你的地图真的需要线程安全吗?
  • 好的或坏的方式会根据您的使用意图而变化。如果您想在 O(1) 时间内获取键的值,最好使用 map。如果您希望映射线程安全,那么并发哈希映射(具有同步开销)是一个好方法。如果你想迭代并按插入顺序做一些过程,你可以使用列表(链接或数组列表)等。那么你的意图是什么?
  • 感谢您的回复。我正在使用带有线程的地图。这只是我项目中的一个示例代码,用于询问是否这是使用 put 的正确方式。所以地图必须是并发的。 (这里忘记拿出来了)

标签: java parsing hashmap bufferedreader


【解决方案1】:

根据the answer from @irreputable的说法,ConcurrentHashMap的性能只比HashMap差一点。因此,除非这里的性能是绝对关键的,或者您确定不需要线程安全,否则您的实现非常好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 2013-02-10
    • 2021-02-13
    • 2010-12-08
    • 1970-01-01
    • 2017-09-05
    • 2022-06-16
    相关资源
    最近更新 更多