问题描述
我有一个 HashMap< Integer,Integer>
.我将其内容写入文件,因此它的每一行都包含 hashmapKey ::: hashmapValue
.我现在是这样的:
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);
我非常怀疑是否需要将整个 HashMap
复制到字符串列表中,我确信在处理大量数据时会给我带来性能问题.我的问题是:如何使用Java 8将 HashMap
内容写入文件,而避免在另一个列表中复制值?
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?
推荐答案
最简单,非复制,最精简"的解决方案是
The simplest, non-copying, most "streamish" solution is
Files.write(mOutputPath, () -> mHashMap.entrySet().stream()
.<CharSequence>map(e -> e.getKey() + DATA_SEPARATOR + e.getValue())
.iterator());
虽然Stream不实现 Iterable
,但是可以执行lambda表达式来执行Stream操作,该操作以在流上调用 iterator()
结尾.它会履行合同,因为lambda表达式将与Stream不同,在每次调用时都会产生一个新的 Iterator
.
While a Stream does not implement Iterable
, a lambda expression performing a Stream operation that ends with calling iterator()
on the stream, can be. It will fulfill the contract as the lambda expression will, unlike a Stream, produce a new Iterator
on each invocation.
请注意,我删除了显式的 UTF-8
字符集说明符,因为 java.nio.Files
将在没有字符集的情况下使用 UTF-8
是指定的(与旧的io类不同).
Note that I removed the explicit UTF-8
character set specifier as java.nio.Files
will use UTF-8
when no charset is specified (unlike the old io classes).
上述解决方案的优点是I/O操作包装了Stream处理,因此在Stream内部,我们不必处理已检查的异常.相反, Writer
+ forEach
解决方案需要处理 IOException
s,因为不允许 BiConsumer
进行检查例外情况.结果,使用 forEach
的可行解决方案如下所示:
The neat thing about the above solution is that the I/O operation wraps the Stream processing, so inside the Stream, we don’t have to deal with checked exceptions. In contrast, the Writer
+forEach
solution needs to handle IOException
s as a BiConsumer
is not allowed to throw checked exceptions. As a result, a working solution using forEach
would look like:
try(Writer writer = Files.newBufferedWriter(mOutputPath)) {
mHashMap.forEach((key, value) -> {
try { writer.write(key + DATA_SEPARATOR + value + System.lineSeparator()); }
catch (IOException ex) { throw new UncheckedIOException(ex); }
});
} catch(UncheckedIOException ex) { throw ex.getCause(); }
这篇关于将HashMap内容写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!