enCrypter enCrypter - 6 months ago 21
Java Question

Writing HashMap contents to the file

I have a

HashMap<Integer, Integer>
. I write its content to the file, so each line of it contains
hashmapKey:::hashmapValue
. This is how I do it now:

List<String> mLines = new ArrayList<String>();
mHashMap.forEach((key, value) -> mLines.add(key + DATA_SEPARATOR + value));
Files.write(mOutputPath, mLines, StandardCharsets.UTF_8);


I very doubt that I need to copy entire
HashMap
to the list of strings, I am sure it will give me performance issues when working with big amounts of data. My question is: how can I write
HashMap
contents to the file using Java 8 avoiding copying values in another list?

Answer

You can simply avoid using a List<String> by directly writing out the lines to disk using e.g. a Writer:

    Writer writer = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(new File(mOutputPath)), StandardCharsets.UTF_8));
    mHashMap.forEach((key, value) -> writer.write(key + DATA_SEPARATOR + value + System.lineSeparator()));
    writer.flush();
    writer.close();