使用parallelStream foreach创建HashMap,但有时值为空

Java代码如:

List DbDetails = ... Like 50000 rows records Map<Long, List> details = new HashMap(); DbDetails .parallelStream().forEach(detail -> { Long id = detail.getId(); details.computeIfAbsent(id, v -> new ArrayList()).add(detail); }); Then ... details.entrySet().stream().forEach(e -> { e.getValue(); // Some value is empty }); 

我猜是因为HashMap是线程不安全的,所以我使用Hashtable而不是它。 然后它运行正常,所有值都有价值,但我不知道为什么?

HashMap不是线程安全的,所以不要使用并行流。

此外,为什么那样,当溪流可以为你做到这一点?

 DbDetails.parallelStream().collect(Collectors.groupingBy(Detail::getId))