Collectors.toConcurrentMap 和通过 Collectors.toMap 供应商选项将 Map 转换为 ConcurrentHashMap 有什么区别?
我想通过 Java 8 Stream
和 Collector
接口将 Map
转换为 ConcurrentHashMap
,然后是我可以使用的两个选项.
I want to convert a Map
into a ConcurrentHashMap
via Java 8 Stream
and Collector
interface, and there are two options I can use.
第一个:
Map<Integer, String> mb = persons.stream()
.collect(Collectors.toMap(
p -> p.age,
p -> p.name,
(name1, name2) -> name1+";"+name2,
ConcurrentHashMap::new));
第二个:
Map<Integer, String> mb1 = persons.stream()
.collect(Collectors.toConcurrentMap(
p -> p.age,
p -> p.name));
哪一个是更好的选择?我应该什么时候使用每个选项?
Which one is the better option? When should I use each option?
推荐答案
它们在处理并行流时是有区别的.
There is a difference between them when dealing with parallel streams.
toMap
-> 是一个非并发收集器
toMap
-> is a non-concurrent collector
toConcurrentMap
-> 是一个并发收集器(这可以从它们的特性上看出来).
toConcurrentMap
-> is a concurrent collector (this can be seen from their characteristics).
不同的是,toMap 会创建多个中间结果,然后会合并在一起(这样的 Collector 的 Supplier 会被调用多次),而 toConcurrentMap 会创建一个单个结果,每个线程都会向它抛出结果(这样的收集器的供应商只会被调用一次)
The difference is that toMap will create multiple intermediate results and then will merge then together (the Supplier of such a Collector will be called multiple times), while toConcurrentMap will create a single result and each Thread will throw results at it (the Supplier of such a Collector will be called only once)
为什么这很重要?这涉及广告订单(如果重要的话).
Why is this important? This deals with insertion order (if that matters).
toMap 将通过合并多个中间结果(多次调用该收集器的供应商以及组合器)以遇到顺序将值插入结果地图中
toMap will insert values in the resulting Map in encounter order by merging multiple intermediate results (Supplier of that collector is called multiple time as well as the Combiner)
toConcurrentMap 将通过将所有元素扔到一个公共结果容器(在本例中为 ConcurrentHashMap)以任何顺序(未定义)收集元素.供应商只被调用一次,累加器被多次调用,而组合器从不被调用.
toConcurrentMap will collect elements in any order (undefined) by throwing all elements at a common result container (ConcurrentHashMap in this case). Supplier is called only once, Accumulator many times and Combiner never.
这里的小警告是 CONCURRENT
收集器不调用合并:流必须具有 UNORDERED
标志 - 通过 unordered()
显式调用或流的源未排序时(例如 Set
).
The small caveat here is that for a CONCURRENT
collector to not invoke the merger: either the stream has to have the UNORDERED
flag - either via the unordered()
explicit call or when the source of the stream is not ordered (a Set
for example).
相关文章