gpt4 book ai didi

java - 我如何知道 Java Stream collect(Collectors.toMap) 是否并行化?

转载 作者:搜寻专家 更新时间:2023-10-31 20:01:01 24 4
gpt4 key购买 nike

我有以下代码尝试通过 Java Stream API 以并行方式从 List 填充 Map:

class NameId {...}

public class TestStream
{
static public void main(String[] args)
{
List<NameId > niList = new ArrayList<>();
niList.add(new NameId ("Alice", "123456"));
niList.add(new NameId ("Bob", "223456"));
niList.add(new NameId ("Carl", "323456"));

Stream<NameId> niStream = niList.parallelStream();
Map<String, String> niMap = niStream.collect(Collectors.toMap(NameId::getName, NameId::getId));
}
}

我如何知道 map 是否使用多线程(即并行)填充?我需要调用 Collectors.toConcurrentMap 而不是 Collectors.toMap 吗?这是并行化 map 人口的合理方法吗?我怎么知 Prop 体的映射是什么支持新的 niMap(例如它是 HashMap)?

最佳答案

来自Javadoc :

The returned Collector is not concurrent. For parallel stream pipelines, the combiner function operates by merging the keys from one map into another, which can be an expensive operation. If it is not required that results are inserted into the Map in encounter order, using toConcurrentMap(Function, Function) may offer better parallel performance.

所以听起来像toConcurrentMap将并行化插入。

默认情况下,支持映射是 HashMap .它只是调用 toMap 的版本这需要 Supplier<M>并通过 HashMap::new . (来源:出处)

关于java - 我如何知道 Java Stream collect(Collectors.toMap) 是否并行化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34099555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com