enCrypter enCrypter - 1 year ago 92
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
. 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
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
contents to the file using Java 8 avoiding copying values in another list?

Answer Source

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()));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download