You can serialize it yourself. You can also compress the data to make it smaller.
public static void write(String filename, Map<String, Set<Long>> data) throws IOException {
try (DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(
new DeflaterOutputStream(new FileOutputStream(filename))))) {
dos.writeInt(data.size());
for (Map.Entry<String, Set<Long>> entry : data.entrySet()) {
dos.writeUTF(entry.getKey());
Set<Long> value = entry.getValue();
dos.writeInt(value.size());
for (Long l : value) {
dos.writeLong(l);
}
}
}
}
To read it you just do the same thing but reading instead of writing.
public static Map<String, Set<Long>> read(String filename) throws IOException {
Map<String, Set<Long>> ret = new LinkedHashMap<>();
try (DataInputStream dis = new DataInputStream(new BufferedInputStream(
new InflaterInputStream(new FileInputStream(filename))))) {
for (int i = 0, size = dis.readInt(); i < size; i++) {
String key = dis.readUTF();
Set<Long> values = new LinkedHashSet<>();
ret.put(key, values);
for (int j = 0, size2 = dis.readInt(); j < size2; j++)
values.add(dis.readLong());
}
}
return ret;
}
public static void main(String... ignored) throws IOException {
Map<String, Set<Long>> map = new LinkedHashMap<>();
for (int i = 0; i < 20000; i++) {
Set<Long> set = new LinkedHashSet<>();
set.add(System.currentTimeMillis());
map.put("key-" + i, set);
}
for (int i = 0; i < 5; i++) {
long start = System.nanoTime();
File file = File.createTempFile("delete", "me");
write(file.getAbsolutePath(), map);
Map<String, Set<Long>> map2 = read(file.getAbsolutePath());
if (!map2.equals(map)) {
throw new AssertionError();
}
long time = System.nanoTime() - start;
System.out.printf("With %,d keys, the file used %.1f KB, took %.1f to write/read ms%n", map.size(), file.length() / 1024.0, time / 1e6);
file.delete();
}
}
prints
With 20,000 keys, the file used 44.1 KB, took 155.2 to write/read ms
With 20,000 keys, the file used 44.1 KB, took 84.9 to write/read ms
With 20,000 keys, the file used 44.1 KB, took 51.6 to write/read ms
With 20,000 keys, the file used 44.1 KB, took 21.4 to write/read ms
With 20,000 keys, the file used 44.1 KB, took 21.6 to write/read ms
So 20K entries in 21 ms and using only 2.2 bytes per entry.