java - 快速静态持久哈希表

标签 java hashtable

我的 Java 应用程序需要一个哈希表来进行计算,并且必须对该哈希表进行数百万次查找。哈希表必须能够非常快速地从磁盘读取到哈希表实用程序中,并且哈希表中的数据是静态的,不需要插入或删除。

您建议使用任何可用的库来执行此操作吗?

此外,数据大小小于200MB。

最佳答案

如果不要求人类可读,您可以喘气仅确保您的数据实现 Serialized 接口(interface)并使用 ObjectOutputStream 序列化 HashMap。它很丑陋,但它可以完成工作。

另一个选项是 DataInputStream 和 DataOutputStream。这些允许您读取/写入结构化二进制数据。

假设你有一个 HashMap,你可以这样写:

// realOutputStream should probably be a BufferedOutputStream
DataOutputStream output = new DataOutputStream( realOutputStream );
for (Map.Entry<Long, String> entry : map.entrySet()) {
    // Write the key
    output.writeLong(entry.getKey().longValue());
    byte bytes[] = entry.getBytes("UTF-8");
    // Writing the string requires writing the length and then the bytes
    output.writeInt(bytes.length);
    output.write(bytes, 0, bytes.length);
}



// realInputStream should probably be a BufferedInputStream
DataInputStream input = new DataInputStream ( realInputStream );
Map<Long, String> map = new HashMap<Long, String>();
while ( true ) {
   try {
     // read the key
     long key = output.readLong();
     // read the string length in bytes
     int strlen = output.readInt();
     // read the bytes into an array
     byte buf[] = new byte[strlen];
     output.readFully(buf, 0, strlen);
     // Create the map entry.
     map.put(Long.valueOf(key), new String(buf,"UTF-8"));
   }
   catch (EOFException e) {
     // input is exhausted
     break;
   }
}

请记住,这是假设您想要以 UTF 格式存储和读取字符串。您可以轻松地不提供字符集并使用 jvm 默认编码。另请注意,像字符串这样长度可变的东西需要您在写入实际数据之前先写入该数据的长度。这样您就可以知道需要读入多少字节来重建该字符串。

关于java - 快速静态持久哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11405421/

相关文章:

dictionary - Hash 可以按键或值排序吗?

hashtable - 分布式哈希表技术和比特币区 block 链有什么区别?

c - 使用哈希表创建无限数组

f# - 分组交替数据

java - 如何创建采用 Generic 对象的 JAXB Marshaller

java - 公历夏令时问题

java - GroupCount 排序依据

java - 使用 Jackson 反序列化期间对列表属性中的对象列表进行分组

java - 使用hibernate懒加载主要有哪些问题?

java - 从JAVA/JSP中的哈希表键值中选择多个选项