我有以下代码尝试通过 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/