Java 代码如下:
List<Detail> DbDetails = ... Like 50000 rows records
Map<Long, List<Detail>> 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代替它。然后运行就ok了,所有的值都有值,但是不知道为什么?
最佳答案
HashMap
不是线程安全的,因此不要使用并行流。
此外,既然流可以为你做到这一点,为什么还要这样做呢?
DbDetails.parallelStream().collect(Collectors.groupingBy(Detail::getId))
关于java - 使用parallelStream foreach创建HashMap,但有时value为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44643621/